i want to display the questions i get from an API one by one. I call the API, parse and store the data, but i don't know how to display each question separately. I can put them in a list view but that's about it. I have a widget with FutureBuilder that calls the API, and i'm currently trying to send data to another widget and manipulate it there using another FutureBuilder (so that i don't keep calling the API when i iterate through the list of questions to display them). I have an integer to keep track of the current position. How should i go about doing this?
Part of the code:
Here i'm trying to send the data to another widget.
FutureBuilder<Reply>(
future: questions(token, id),
builder: (context, snapshot) {
if (snapshot.hasError) {
print('Error : ${snapshot.error}'); //show error on the terminal
return Text('Error : ${snapshot.error}'); //show error on the app
} else if (snapshot.hasData) {
reply = snapshot.data;
return Show_Questions(reply: reply,);
} else {
return Center(child: CircularProgressIndicator()); //else display a loading indicator
} //loading indicator
}
),
Any help is appreciated. I can post more code if needed.
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new FutureBuilder(
future: questions(token, id),
initialData: [],
builder: (context, snapshot) {
return createListView(context, snapshot);
}),
);
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
var values = snapshot.data;
return ListView.builder(
itemCount: values == null ? 0 : values.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
});
},
child: Column(
children: <Widget>[
new ListTile(
title: Text(values[index]),
),
Divider(
height: 2.0,
),
],
),
);
},
);
}
}
hopefully help you :)
Related
As someone new to Flutter/Dart, I have a simplistic proof-of-concept web app (code provided below) where I've genuinely put the effort in to reading & prototyping but cannot quite get the code finished.
The app is a test of named routes. FirstScreen uses an ElevatedButton to jump to SecondScreen. SecondScreen can only return to FirstScreen via the Back arrow in SecondScreen's AppBar, but I also want the ability to dynamically hide that Back arrow if the app is started from SecondScreen, or enable it if the app is started from FirstScreen. Why ? Because the idea is to provide the option to run SecondScreen in a kiosk mode where the user's navigation is restricted to that one route of the app.
I designed the code to use a ChangeNotifier/Consumer approach using Flutter's "provider" package. The state is provided by the routedViaHome boolean (default is false) in RouteMonitor. The only time the boolean should be set true is if the app starts at FirstScreen and the user clicks the ElevatedButton to go to SecondScreen; that change is observed by SecondScreen and should be used to dynamically set its own AppBar 'automaticallyImplyLeading' property.
My question is this: the Consumer is correctly displaying the Text widget, but how do I ALSO get it to update the automaticallyImplyLeading property ? What am I missing please and/or have I needlessly complicated this ?
Thank you !
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => RouteMonitor(),
child: const MyApp(),
)
);
}
class RouteMonitor with ChangeNotifier {
bool routedViaHome = false;
void routeViaHome() {
routedViaHome = true;
notifyListeners();
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => const FirstScreen(),
'/second': (context) => const SecondScreen(),
},
);
}
}
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Provider.of<RouteMonitor>(context, listen: false).routeViaHome();
Navigator.pushNamed(context, '/second');
//Navigator.pushReplacementNamed(context, '/second');
},
child: const Text('Launch screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Screen'),
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This is static data but no navigation'),
Consumer<RouteMonitor>(
builder: (context, routemonitor, child) => Text(
'${routemonitor.routedViaHome}',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
);
}
}
This question already has answers here:
Error: The instance member ... can't be accessed in an initializer
(4 answers)
Closed 4 months ago.
I always get this error when I use the String "name" to locate my Firestore docs. I don't understand why this is happening bc when I use "user.uid" it just works.
The instance member 'name' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
This is my code:
final user = FirebaseAuth.instance.currentUser!;
class Folder extends StatelessWidget {
Folder(this.name, {super.key});
final String name;
final Stream<QuerySnapshot> items = FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.collection('Folder')
.doc(name)
.collection('Items')
.snapshots();
#override
Widget build(BuildContext context) {
return Column(
children: [
// Title
Text(name, style: Theme.of(context).textTheme.headlineSmall),
// List with Items
StreamBuilder(
stream: items,
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final data = snapshot.requireData;
if (snapshot.hasData) {
return ListView.builder(
itemCount: data.size,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return ListTile(
title: Text(data.docs[index]['name']),
onTap: () {},
);
},
);
}
if (snapshot.hasError) {
return const Text("error");
}
return const Text("error");
},
),
],
);
}
}
And I pass the String from this StreamBuilder:
stream: folder,
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
final data = snapshot.requireData;
if (snapshot.hasError) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(00.0),
child: ListView.builder(
padding: const EdgeInsets.only(bottom: 100, top: 20),
itemCount: data.size,
itemBuilder: (context, index) {
return Folder(
data.docs[index]["name"].toString()
);
},
),
);
}
return const Center(child: CircularProgressIndicator());
},
),
You could just add a late modifier to the items variable. Like this:
late final Stream<QuerySnapshot> items = FirebaseFirestore.instance
.collection('users')
.doc(user.uid)
.collection('Folder')
.doc(name)
.collection('Items')
.snapshots();
To explain why this works: basically you can't use any instance variables when initializing other instance variables because they are all initialized when the class gets instantiated. When you add the late modifier, the variable will only be initialized when it's first used, meaning all the non-late variables will already be initialized.
I am sending the GET request to the flutter app from the express API but I am not getting any output in the flutter App. The API is working in the postman and I am getting the perfect output in the postman.
Please help
testing() async{
debugPrint("Hello");
http.Response response = await
http.get("http://192.168.119.97:3000/api/cricketer");
debugPrint((response.body));
debugPrint("Hello hy");
}
Future getData() async {
http.Response response = await
http.get("http://192.168.119.97:3000/api/cricketer");
debugPrint((response.body));
data = json.decode(response.body);
debugPrint(('$data'));
setState(() {
userData = data["cricketers"];
debugPrint("Hello ");
debugPrint(('$userData'));
});
}
Calling the Function:
#override
void initState() {
super.initState();
getData();
testing();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Cricketer Info"),
backgroundColor: Colors.pink,
),
body: ListView.builder(
itemCount: userData == null ? 0 : userData.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
children: <Widget>[
// CircleAvatar(
// backgroundImage: NetworkImage(userData[index][""]),
// ),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text("${userData[index]["name"]}",
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.w700,
),),
)
],
),
),
);
},
),
);
}
}
I have uploaded the code also. Please check and if possible help
First, you have to JSON decode the body for print, json.decode() gives some misleading. You can use jsonDecode(result.body) from 'dart:convert' package . Here I have attached some
example codes of login(Post request). After decoding you can use a data model and factory method to convert to a dart object.
repo dart file that send post request
my data model with a factory method for decode json to dart
I have a ListView which holds ListTiles. Each tile represents a user of my users array. The trailing of a tile is a PopupMenuButton. When the user clicks on one PopupMenuItem, a function shall be called. So far so good. In the "onSelected" I would like to pass data of the corresponding user to a function.
Could anybody please give me a hint, how I should change the code to be able to do so?
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:flutter/material.dart';
class UserListMobilePortrait extends StatelessWidget {
final List<QueryDocumentSnapshot> users;
const UserListMobilePortrait({
Key key,
this.users,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final HttpsCallable setRoleCallable = CloudFunctions.instance
.getHttpsCallable(functionName: 'setRoles')
..timeout = const Duration(seconds: 10);
final button = new PopupMenuButton(
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
child: const Text('Make Admin'), value: 'admin'),
new PopupMenuItem<String>(
child: const Text('Make Editor'), value: 'editor'),
],
onSelected: (selectedItem) async {
try {
final HttpsCallableResult result = await setRoleCallable.call(
<String, dynamic>{
//'user' shall represent the user of the clicked ListTile, but how to pass it?
'email': user.data()['email'],
'role': selectedItem,
'permission': 'grant'
},
);
print(result.data);
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
});
return ListView(
children: users
.map((user) => ListTile(
title: Text(
(user.data()['email'] != null) ? user.data()['email'] : ""),
subtitle: Row(
children: [
Text((user.data()['displayName'] != null)
? user.data()['displayName']
: ""),
Container(
width: 6,
),
user.data()['isAdmin'] == true
? Chip(
label: Text('admin'),
backgroundColor: Colors.orange[600],
shadowColor: Colors.orange[900],
)
: Text(''),
Container(
width: 6,
),
user.data()['isEditor'] == true
? Chip(
label: Text('editor'),
backgroundColor: Colors.blue[600],
shadowColor: Colors.blue[900],
)
: Text(''),
],
),
trailing: button,
))
.toList(),
);
}
}
understanding your problem a simple workaround will be to use a Listview Builder(And also using a ListView Builder will optmize the app for speed)
const List = ["Hello", "World", "Temp"]
ListView.builder(
itemBuilder: (context, index) {
//return (Your widget [a list tile preferably and use onTap(and access the index
in the function)])
return(ListTile(onTap:(){
print(List[index]);
//you can access the index and use the main list to get its following data
};
};
This will workout :)
My solution was moving the former final button to its own class. So I can pass the data to the constructor.
UserPopupMenuButton
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_functions/cloud_functions.dart';
import 'package:flutter/material.dart';
class UserPopupMenuButton extends StatelessWidget {
final QueryDocumentSnapshot user;
const UserPopupMenuButton({
Key key,
this.user,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final HttpsCallable setRoleCallable = CloudFunctions.instance
.getHttpsCallable(functionName: 'setRoles')
..timeout = const Duration(seconds: 10);
return PopupMenuButton(
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
child: const Text('Make Admin'), value: 'admin'),
new PopupMenuItem<String>(
child: const Text('Make Editor'), value: 'editor'),
],
onSelected: (selectedItem) async {
try {
final HttpsCallableResult result = await setRoleCallable.call(
<String, dynamic>{
'email': user.data()['email'],
'role': selectedItem,
'permission': 'grant'
},
);
print(result.data);
} on CloudFunctionsException catch (e) {
print('caught firebase functions exception');
print(e.code);
print(e.message);
print(e.details);
} catch (e) {
print('caught generic exception');
print(e);
}
});
}
}
And using it as the trailing for the ListTile:
trailing: UserPopupMenuButton(user: user),
I am building a flutter web using old version. I am having a FileUploadInputElement. I need to get the file selected from that element.
#override
Widget build(BuildContext context) {
FileUploadInputElement fileUploadInputElement = FileUploadInputElement();
ui.platformViewRegistry.registerViewFactory(
'animation-Image-html', (int viewId) => fileUploadInputElement);
return SizedBox(
child: HtmlElementView(
viewType: 'animation-Image-html',
),
);
}
You can directly use the element.files property to access the files and use the Filreader class from dart:html. I have created an example below to show you how a text file and image can be read. This example is based on FileReader examples in another post.
Accessing the file
Here element is the FileUploadInputElement reference.
element.files[0] or in case of multiple files element.files
Set up your file reader
String option1Text = "Initialized text option1";
Uint8List uploadedImage;
FileUploadInputElement element = FileUploadInputElement()..id = "file_input";
// setup File Reader
FileReader fileReader = FileReader();
Use FileReader to read the file
fileReader.readAsText(element.files[0])
connect the listener for load event
fileReader.onLoad.listen((data) {
setState(() {
option1Text = fileReader.result;
});
});
connect error events
fileReader.onError.listen((fileEvent) {
setState(() {
option1Text = "Some Error occured while reading the file";
});
});
Use Image.memory to show images from byte array.
Image.memory(uploadedImage)
Note: In the following example we choose a file and click the respective button to handle the file reading. But the same can be achieved by connecting the logic in respective events of the FileUploadInputElement element in a similar approach. eg: element.onLoad.listen or element.onError.listen event streams.
Full Example
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'dart:html';
class FileUploadTester extends StatefulWidget {
#override
_FileUploadTesterState createState() => _FileUploadTesterState();
}
class _FileUploadTesterState extends State<FileUploadTester> {
String option1Text = "Initialized text option1";
Uint8List uploadedImage;
FileUploadInputElement element = FileUploadInputElement()..id = "file_input";
// setup File Reader
FileReader fileReader = FileReader();
// reader.onerror = (evt) => print("error ${reader.error.code}");
#override
Widget build(BuildContext context) {
ui.platformViewRegistry.registerViewFactory("add_input", (int viewId) {
return element;
});
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
FlatButton(
color: Colors.indigoAccent,
child: Text('ReadFile'),
onPressed: () {
fileReader.onLoad.listen((data) {
setState(() {
option1Text = fileReader.result;
});
});
fileReader.onError.listen((fileEvent) {
setState(() {
option1Text = "Some Error occured while reading the file";
});
});
fileReader.readAsText(element.files[0]);
},
),
Expanded(
child: Container(
child: Text(option1Text),
),
),
Expanded(child: HtmlElementView(viewType: 'add_input')),
Expanded(
child: uploadedImage == null
? Container(
child: Text('Uploaded image should shwo here.'),
)
: Container(
child: Image.memory(uploadedImage),
),
),
FlatButton(
child: Text('Show Image'),
color: Colors.tealAccent,
onPressed: () {
fileReader.onLoad.listen((data) {
setState(() {
uploadedImage = fileReader.result;
});
});
fileReader.onError.listen((fileEvent) {
setState(() {
option1Text = "Some Error occured while reading the file";
});
});
fileReader.readAsArrayBuffer(element.files[0]);
},
),
],
);
}
}
Below
Image Upload in Flutter Web - Working perfectly fine for me :)
startFilePicker() async {
FileUploadInputElement uploadInput = FileUploadInputElement();
uploadInput.multiple = true;
uploadInput.draggable = true;
uploadInput.click();
uploadInput.onChange.listen((e) {
// read file content as dataURL
final files = uploadInput.files;
print(files);
if (files != null && files.isNotEmpty) {
for (var i = 0; i < files.length; i++) {
FileReader reader = FileReader();
reader.onLoadEnd.listen((e) async {
if (reader.result != null) {
Uint8List? _byteData = reader.result as Uint8List;
// upload the image
}
});
reader.onError.listen((fileEvent) {
Fluttertoast.showToast(
msg: "Some Error occured while reading the file");
});
reader.readAsArrayBuffer(files[i]);
}
} else {
Fluttertoast.showToast(msg: 'Images not selected');
}
});
}