How to to display text over the images in Flutter? - android

I want to display the text over the images in Listview. I am able to see the Images and text but text will showing at left top corner. I want to display it on each text over the each images. Below is my code. Please help me
import 'dart:async';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('url here');
return compute(parsePhotos, response.body);
}
// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody);
return (parsed["data"]["categoryList"] as List)
.map<Photo>((json) => new Photo.fromJson(json))
.toList();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return new MyHomePage();
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new FutureBuilder<List<Photo>>(
future: fetchPhotos(new http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? new PhotosList(photos: snapshot.data)
: new Center(child: new CircularProgressIndicator());
},
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
#override
Widget build(BuildContext context) {
return _buildBody();
}
Widget _buildBody() {
return new Stack(
children: <Widget>[
new Positioned(
child: new Container(
child: new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return new Text(photos[int].title);
}
),
)
),
new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return new CachedNetworkImage(imageUrl: photos[int].url);
}
),
],
);
}
}
class Photo {
final int catID;
final String title;
final String url;
final String thumbnailUrl;
final String description;
final String webstiteURL;
Photo(
{this.catID,
this.title,
this.url,
this.thumbnailUrl,
this.description,
this.webstiteURL});
factory Photo.fromJson(Map<String, dynamic> json) {
return new Photo(
catID: json['category_id'] as int,
title: json['category_name'] as String,
url: json['category_img'] as String,
thumbnailUrl: json['thumb_img'] as String,
description: json['description'] as String,
webstiteURL: json['website_url'] as String,
);
}
}

You can use a Stack widget for that:
Stack(
children: <Widget>[
yourImageWidget,
Center(child: Text("someText")),
]
)
PhotosList class:
PhotosList({Key key, this.photos}) : super(key: key);
#override
Widget build(BuildContext context) {
return _buildBody();
}
Widget _buildBody() {
return new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return Stack(
children: <Widget> [
new CachedNetworkImage(imageUrl: photos[int].url),
Center(child: Text(photos[int].title)),
]
);
}
);
}
}

try this
Container(
child: Center(child: Text('test'),),
height: 190.0,
width: MediaQuery.of(context).size.width - 100.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.blue,
image: DecorationImage(
image: new NetworkImage(
"https://storage.googleapis.com/gd-wagtail-prod-assets/original_images/MDA2018_inline_03.jpg"
),
fit: BoxFit.fill
)
),
),

I find this worked a bit better and you don't need the Center widget:
Stack(
alignment: Alignment.center,
children: <Widget>[
yourImageWidget,
Text("someText"),
]
)

Just want to add a small example of Stack Widget
return Scaffold(
appBar: AppBar(
title: Text("Text Over Image"),
),
body: Center(
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
child: Image.network(
'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg',
height: 250,
width: double.infinity,
fit: BoxFit.cover,
),
),
Container(
alignment: Alignment.center,
child: Text(
'Text Message',
style: TextStyle(color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 22.0),
)),
],
),
),
);
Output:
You can read more in my article on medium.com

try this
Card(
elevation: 4,
margin: EdgeInsets.fromLTRB(0.0, 4.0, 4.0, 4.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4.0),
),
shadowColor: Colors.white,
color: Colors.white70,
child: Stack(children: <Widget>[
Center(
child: Image(
image: NetworkImage(ApiContent.PREF_IMAGES_PATH +
_listMomentListModel[index].filePath),
),
),
Column(mainAxisAlignment: MainAxisAlignment.end, children: [
Container(
width: double.infinity,
color: Colors.white,
padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
child: Text(
_listMomentListModel[index].title,
maxLines: 5,
textAlign: TextAlign.center,
)),
]),
]),
);
to set text bottom
mainAxisAlignment: MainAxisAlignment.end,
to set text top
mainAxisAlignment: MainAxisAlignment.start,
to set text center
mainAxisAlignment: MainAxisAlignment.center,

Example of Text over background-image using Stack.
body: SafeArea(
child: Stack(
children:[
Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("Assets/splash_images/splash.png",),fit: BoxFit.cover,
),
),
),
Column(
children: const [
Center(
child: Text("Text is Here ",style:TextStyle(fontSize: 20),)
,
)
],
)
]),
)
**
Click Here For Output
**

Related

Newsapi.org not displaying full content

I am trying to create a news app using api provided by newsapi.org
but the content is appearing as follows.. I am using a free api key
The code for the displaying and retrieving the data from api is given below
import 'package:flutter/material.dart';
import 'package:news_api_flutter_package/model/article.dart';
import 'package:news_api_flutter_package/news_api_flutter_package.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class NewsPage extends StatefulWidget {
const NewsPage({Key? key, required this.category}) : super(key: key);
final String category;
#override
State<NewsPage> createState() => _NewsPageState();
}
class _NewsPageState extends State<NewsPage> {
final NewsAPI _newsAPI = NewsAPI("MyAPIKEY");
final spinkit = const SpinKitSpinningLines(
color: Colors.yellow,
size: 150.0,
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Article>>(
future:
_newsAPI.getTopHeadlines(country: "in", category: widget.category),
builder: (context, snapshot) {
if (snapshot.hasData) {
return PageView.builder(
itemCount: snapshot.data!.length,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
return Column(
children: [
SizedBox(
height: 250,
width: MediaQuery.of(context).size.width,
child: FittedBox(
fit: BoxFit.fill,
child: Image.network(
snapshot.data![index].urlToImage.toString(),
fit: BoxFit.fill,
)),
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.all(20),
child: Text(
snapshot.data![index].title.toString(),
style: const TextStyle(fontSize: 22),
),
)),
Padding(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Text(
snapshot.data![index].content.toString(),
style: Theme.of(context).textTheme.subtitle1,
),
)
],
);
});
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else {
return Container(
child: spinkit,
);
}
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.pop(context);
},
backgroundColor: Colors.yellow,
child: const Icon(Icons.arrow_back),
),
);
}
}
Is there any possibility to get the whole content. The api key has been removed for obvious reason
#R3hankhan According to the newsApi docs
https://newsapi.org/docs/endpoints/top-headlines
The response object has a key called totalResults which is an int and shows the number of articles fetched. so in your PageView.builder() itemCount will be snapshot.data!.totalResults (see the docs). And the other property called articles can be used to map over and display the ui accordingly. See the docs for further reference.

How to use Streambuilder in flutter

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
//Run this first
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Smart Bin',
home: new HomePageWidget(),
);
}
}
class HomePageWidget extends StatefulWidget {
const HomePageWidget({Key key}) : super(key: key);
#override
_HomePageWidgetState createState() => _HomePageWidgetState();
}
class _HomePageWidgetState extends State<HomePageWidget> {
final scaffoldKey = GlobalKey<ScaffoldState>();
final currentBinRecord = FirebaseFirestore.instance.collection("current_bin");
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text(
'SmartBin',
),
),
body: SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: StreamBuilder<List<CurrentBinRecord>>(
stream: queryCurrentBinRecord(
queryBuilder: (currentBinRecord) =>
currentBinRecord.orderBy('level', descending: true),
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator(),
),
);
}
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: listViewCurrentBinRecordList.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
listViewCurrentBinRecordList[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
},
),
),
],
),
),
),
);
}
}
This is the error
First error is on:
child: StreamBuilder<List<CurrentBinRecord>>
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
Second error is on:
stream: queryCurrentBinRecord
The method 'queryCurrentBinRecord' isn't defined for the type '_HomePageWidgetState'.
Try correcting the name to the name of an existing method, or defining a method named 'queryCurrentBinRecord'.
Third error is on:
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
These is the syntax try -
return StreamBuilder(
stream: theStreamSource, // Eg a firebase query
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, int index) {
return Text(snapshot.data.documents[index]['title']);
}
);
},
);
Hope it helps.
I think the best way to use StreamBuilder is to create separate controller class that can handle all your business logic and update UI.
// your widget class
class UIClass extends StatefulWidget {
const UIClass({Key key}) : super(key: key);
#override
_UIClassState createState() => _UIClassState();
}
class _UIClassState extends State<UIClass> {
UIClassController<List<CurrentBinRecord>> _uiController;
#override
void initState() {
_uiController = UIClassController(StreamController<List<CurrentBinRecord>>());
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Text("Hello Everyone"),
StreamBuilder<List<CurrentBinRecord>>(
stream: _uiController.uiStream,
builder: (context, snapshot) {
if(snapshot.hasError){
return ErrorWidget();
}
else if(snapshot.connectionState == ConnectionState.waiting){
return WaitingWidget();
}
else if(snapshot.hasData){
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: snapshot.data.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
snapshot.data[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
}
else{
return SizedBox();
}
}
),
],
);
}
#override
void dispose() {
super.dispose();
_uiController.dispose();
}
}
// controller class to handle all business logic
// you can also split it into multiple sub controllers
class UIClassController<T> {
final StreamController<T> _controller;
// If you are using this on multiple widgets then use asBroadcastStream()
Stream<T> get uiStream => _controller.stream;
UIClassController(this._controller);
void updateMyUI([dynamic params]){
T t;
// your logic //
//------------//
_controller.sink.add(t);
}
void dispose(){
_controller.close();
}
}
Code I'm Using for StreamBuilder
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../door/widgets/Navbar.dart';
import '../door/widgets/sidenav.dart';
import 'package:get/get.dart';
FirebaseAuth auth = FirebaseAuth.instance;
class CartPage extends StatefulWidget {
#override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
final FirebaseFirestore fb = FirebaseFirestore.instance;
int up = 1;
bool loading = false;
final ScrollController _scrollController = ScrollController();
#override
void initState() {
super.initState();
getCartData();
}
void addMore(qty, documentID) {
int new_qty = qty + 1;
Get.snackbar('Qty! ', new_qty.toString());
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Added'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
void minusMore(qty, documentID) {
if (qty > 1) {
int new_qty = qty - 1;
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Subtracted'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
}
Stream<QuerySnapshot> getCartData() {
String collection_name = "cart_${auth.currentUser?.email}";
return FirebaseFirestore.instance
.collection(collection_name)
.orderBy("created_at", descending: false)
.snapshots();
}
final ButtonStyle style = ElevatedButton.styleFrom(
minimumSize: Size(50, 30),
backgroundColor: Color(0xFFFFB61A),
elevation: 6,
textStyle: const TextStyle(fontSize: 11),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
)));
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: Navbar.navbar(),
drawer: Sidenav.sidenav(),
body: Container(
padding: EdgeInsets.all(10.0),
child: StreamBuilder<QuerySnapshot>(
stream: getCartData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return buildText('Something Went Wrong Try later');
} else {
if (!snapshot.hasData) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 100,
minHeight: 190,
maxWidth: 200,
maxHeight: 200,
),
child: Icon(Icons.shopping_cart, size: 45),
),
title: Text('No Food!'),
subtitle: const Text('Your cart is empty!'),
),
],
),
);
} else {
return ListView.builder(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: 90.0,
child: Card(
elevation: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const SizedBox(
width: 20,
),
_buildImg('assets/logo.png', '60', '60'),
const SizedBox(
width: 14,
),
SizedBox(
width:
MediaQuery.of(context).size.width *
0.33,
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 20,
),
Text(
snapshot.data?.docs[index]
["name"],
maxLines: 2,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14)),
const SizedBox(
height: 5,
),
Text(
"₹${snapshot.data?.docs[index]["price"]}",
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 12)),
],
),
),
const SizedBox(
width: 10,
),
Container(
margin: const EdgeInsets.only(
top: 20.0, bottom: 10.0),
decoration: BoxDecoration(
color: const Color(0xFFFFB61A),
// color: Color(0xFF0A2031),
borderRadius:
BorderRadius.circular(17)),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment:
CrossAxisAlignment.end,
children: <Widget>[
SizedBox(
height: 40,
child: IconButton(
onPressed: () {
minusMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
color: Colors.white,
icon:
const Icon(Icons.remove)),
),
const SizedBox(
width: 5,
),
Container(
margin: const EdgeInsets.only(
bottom: 10.0),
child: Text(
"${snapshot.data?.docs[index]["qty"]}",
style: const TextStyle(
fontWeight:
FontWeight.w400,
color: Colors.white,
fontSize: 16)),
),
const SizedBox(
width: 5,
),
SizedBox(
height: 40,
child: IconButton(
color: Colors.white,
onPressed: () {
addMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
icon: const Icon(Icons.add)),
),
],
),
),
const SizedBox(
width: 10,
),
],
),
),
);
});
}
}
}
},
),
),
);
}
Widget buildText(String text) => Center(
child: Text(
text,
style: TextStyle(fontSize: 24, color: Colors.black),
),
);
_buildImg(img, hei, wid) {
return Container(
alignment: Alignment.center, // use aligment
child: Image.asset(
img,
height: double.parse(hei),
width: double.parse(wid),
fit: BoxFit.cover,
),
);
}
}

Problem navigating to a route with Dialogflow and Flutter

I am working on an application with Flutter and Dialogflow and I want to make that when I say something specific to the bot, it will take me to a screen. That is, when writing 'depresion', I want it to take me to the context of the id to which 'depresion' corresponds. I have already created an Entitie in Dialogflow 'cual' with the id of the context I want to go to, but now I am not even shown the messages from the bot and it throws me this error.
UPDATE
This is the conversation that I usually have with the bot and it appears before placing the code that appears commented to use the parameters. The idea is that when that "3" appears, it takes me to the context screen that corresponds to that id "3" that I indicate in Navigator.pusnNamed
Flutter error
Dialogflow Entitie
class dialog_flow.dart
class FlutterFactsDialogFlow extends StatefulWidget {
FlutterFactsDialogFlow({Key key, this.title}) : super(key: key);
final String title;
#override
_FlutterFactsDialogFlowState createState() => new _FlutterFactsDialogFlowState();
}
class _FlutterFactsDialogFlowState extends State<FlutterFactsDialogFlow> {
final List<FactsMessage> _messages = <FactsMessage>[];
final TextEditingController _textController = new TextEditingController();
TtsProvider ttsProvider = TtsProvider();
Widget _queryInputWidget(BuildContext context) {
return Container(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
child: Row(
children: <Widget>[
Flexible(
child: TextField(
controller: _textController,
onSubmitted: _submitQuery,
decoration: InputDecoration.collapsed(hintText: "Envia un mensaje"),
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: Icon(Icons.send),
onPressed: () => _submitQuery(_textController.text)),
),
],
),
),
);
}
void _dialogFlowResponse(context, query) async {
_textController.clear();
AuthGoogle authGoogle =
await AuthGoogle(fileJson: "assets/key.json").build();
Dialogflow dialogFlow =
Dialogflow(authGoogle: authGoogle, language: Language.spanish);
AIResponse response = await dialogFlow.detectIntent(query);
print(response.queryResult.parameters['cual']);
int id = int.parse(response.queryResult.parameters['cual']);
Navigator.pushNamed(context, 'home', arguments: id);
FactsMessage message = FactsMessage(
text: response.getMessage() ??
CardDialogflow(response.getListMessage()[0]).title,
name: "PsyBot",
type: false,
);
ttsProvider.hablar(response.getMessage());
setState(() {
_messages.insert(0, message);
});
}
void _submitQuery(String text) {
_textController.clear();
FactsMessage message = new FactsMessage(
text: text,
name: "Tú",
type: true,
);
setState(() {
_messages.insert(0, message);
});
_dialogFlowResponse(context, text);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("PsyBot"),
),
body: Column(children: <Widget>[
Flexible(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
reverse: true, //Para mantener los últimos mensajes al final
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
)),
Divider(height: 1.0),
Container(
decoration: new BoxDecoration(color: Theme.of(context).cardColor),
child: _queryInputWidget(context),
),
]),
);
}
}
class fact_message.dart
class FactsMessage extends StatelessWidget {
FactsMessage({this.text, this.name, this.type});
final String text;
final String name;
final bool type;
List<Widget> botMessage(context) {
return <Widget>[
Container(
margin: const EdgeInsets.only(right: 16.0),
child: CircleAvatar(child: Text('Bot')),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(this.name,
style: TextStyle(fontWeight: FontWeight.bold)),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
];
}
List<Widget> userMessage(context) {
return <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(this.name, style: Theme.of(context).textTheme.subtitle1),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
Container(
margin: const EdgeInsets.only(left: 16.0),
child: CircleAvatar(child: new Text(this.name[0])),
),
];
}
#override
Widget build(BuildContext context) {
return new Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this.type ? userMessage(context) : botMessage(context),
),
);
}
}
class home_page.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
PageController pageController = PageController(initialPage: 0);
int pageChanged = 0;
TtsProvider ttsProvider = TtsProvider();
#override
Widget build(BuildContext context) {
final preguntaP = Provider.of<PreguntaProvider>(context);
final int idTest = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
actions: [
IconButton(icon: Icon(Icons.arrow_forward_ios), onPressed: (){
pageController.nextPage(duration: Duration(milliseconds: 150), curve: Curves.bounceInOut );
})
],
),
body: FutureBuilder<List<Pregunta>>(
future: preguntaP.fetchPreguntas(idTest),
builder: (context, AsyncSnapshot<List<Pregunta>> snapshot) {
if (snapshot.hasData){
// ttsprovider
//ttsProvider.hablar("Prueba");
List<Pregunta> preg = snapshot.data;
return PageView(
physics: new NeverScrollableScrollPhysics(),
pageSnapping: true,
reverse: false,
controller: pageController,
onPageChanged: (index){
setState(() {
pageChanged = index;
});
},
children: armarPreguntas(preg),
);
} else{
return Center(child: CircularProgressIndicator());
//return Container();
}
}
),
);
}
List<Widget> armarPreguntas(List<Pregunta> listaPreguntas){
final List<Widget> listadoWidget = [];
for (Pregunta item in listaPreguntas) {
listadoWidget.add(Pagina(item, pageController));
}
return listadoWidget;
}
}

Failed Assertion: boolean expression must not be null. Initially the loading screen is called

My code is as follows:
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<CategoryModel> categories = new List<CategoryModel>();
List<ArticleModel> articles = new List<ArticleModel>();
bool _loading = true;
getNews() async{
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
setState(() {
_loading = false;
});
}
#override
void initState() {
getNews();
categories = getCategories();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("News"),
Text("App", style: TextStyle(
color: Colors.blueAccent
),)
],
),
centerTitle: true,
elevation: 0.0,
),
body: _loading ? Center(
child: CircularProgressIndicator(),
) : SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Column(
children: <Widget>[
/// Categories
Container(
height: 70,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categories.length,
itemBuilder: (context, index){
return CategoryTile(
imageUrl: categories[index].imageUrl,
categoryName: categories[index].categoryName,
);
}),
),
/// Blog
Container(
padding: EdgeInsets.only(top: 16),
child: ListView.builder(
itemCount: articles.length,
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemBuilder: (context, index){
return BlogTile(
imageUrl: articles[index].urlToImage,
title: articles[index].title,
desc: articles[index].description,
);
}),
)
],
),
),
),
);
}
}
class CategoryTile extends StatelessWidget {
final imageUrl, categoryName;
CategoryTile({this.imageUrl, this.categoryName});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
},
child: Container(
margin: EdgeInsets.only(right: 16),
child: Stack(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: CachedNetworkImage(
imageUrl: imageUrl, width: 120, height: 60, fit: BoxFit.cover,)
),
Container(
alignment: Alignment.center,
width: 120, height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Colors.black26,
),
child: Text(categoryName, style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w500
),),
)
],
),
),
);
}
}
class BlogTile extends StatelessWidget {
final String imageUrl, title, desc;
BlogTile({#required this.imageUrl,#required this.title,#required this.desc});
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.network(imageUrl)
),
SizedBox(height: 8,),
Text(title, style: TextStyle(
fontSize: 17, color: Colors.black87, fontWeight: FontWeight.w500
),),
SizedBox(height: 8,),
Text(desc, style: TextStyle(
color: Colors.black54
),)
],
),
);
}
}
When I run the code it shows the loading screen which is not going off, the content which i want to display is not showing. Please help by providing your valuable answer. Thank you in advance.
The error I am getting is as follows:
E/flutter ( 5339): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Failed assertion: boolean expression must not be null
Since you are initialising your _loading variable inside the first statement of the initState. You can as well initialise it directly when declaring it.
Like this:
bool _loading = true;
Try the code below:
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<CategoryModel> categories = new List<CategoryModel>();
List<ArticleModel> articles = new List<ArticleModel>();
bool _loading = true;
getNews() async{
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
}
#override
void initState() {
getNews();
categories = getCategories();
setState(() {
_loading = false;
});
super.initState();
}
I hope this helps.

How to call a method from another class in flutter

I'm Beginner to coding. I have created a Image picker in flutter, I want to use the image picker in many different pages, so I have created a separate class, but when I call the method in other pages, it just open the gallery but,it is not picking the image from gallery and displaying the picked image.There is no any error.
Kindly, help to solve the issue.
Thanks in advance
My Code:
main.dart:
import 'package:flutter/material.dart';
import 'package:project1test/healthscreen_expat.dart';
import 'package:project1test/forms/parkings.dart';
class accomodationform extends StatefulWidget {
String text;
accomodationform(String name) {
text = name;
}
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return MyAppState(text);
}
}
class MyAppState extends State<accomodationform> {
Mod1 mod11 = new Mod1();
String labels;
MyAppState([String label]) {
labels = label;
}
Image1 im = Image1();
final scaffoldkey = new GlobalKey<ScaffoldState>();
final formkey = new GlobalKey<FormState>();
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(
key: formkey,
child: ListView(children: <Widget>[
mod11.user(),
]))),
);
}
}
imagepick.dart
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Mod1 {
var images1accom;
user() {
List<dynamic> img = List();
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
Well, I think maybe it would be good for you to study object-oriented programming, dart, and how Flutter works.
Initially, I need to tell you that you simply cannot do what you are trying to do, insert widgets within classes, with separate functions, and try to instantiate it within a Stateful.
Widgets must not be instantiated, and if you want to componentize something, you must do it using a stateful or stateless class, not an ordinary class.
Your Mod class should look like this:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
setState(() {});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
And you can to use it with
child: ChoosePic()
I have no idea why you are using a listview in your main class, but if it is really necessary, you would do this:
ListView(children: <Widget>[
ChoosePic(),
])
If you want the value of img, you will need a state manager for this:
Using Get (add this package to pubspec):
https://pub.dev/packages/get
Create class with shared state:
class Controller extends GetController {
static Controller get to => Get.find();
List<dynamic> img = List();
takeImage() {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
update(this);
}
}
// use it:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
Controller.to.takeImage();
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
}
),
),
],
),
),
);
}
}
Now you can get the image list from anywhere in your code with:
on widget three controller.img;
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
Example:
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
And take it out of the widget tree with:
Controller.to.img
Note: init: Controller() can only be used once, if you need GetBuilder elsewhere, don't use it. Use, for example:
GetBuilder<Controller>(
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
Well, I shouldn't answer that, as it qualifies as a general question, but since you are a beginner, I answered to help you, in detail. I hope you understand the basics soon, and become a great developer someday.
Welcome to Flutter!
You need to create a separate widget for Mod1 class.
MyAppState
Widget build(BuildContext context) {
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(key: formkey, child: Mod1())),
);
}
Mod1 widget
class Mod1 extends StatefulWidget {
#override
State<StatefulWidget> createState() => Mod1State();
}
class Mod1State extends State<Mod1> {
var images1accom;
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
img.add(images1accom);
});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
if you want to use a method in different pages you can use Providers

Categories

Resources