Flutter list build - list

void getData() {
Firestore.instance
.collection(collectionName)
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
String text = '${f.data}'.split(":")[0].substring(1);
print(text);
});
});
}
that code get to console,
I/flutter (25628): Country
I/flutter (25628): Meals
I/flutter (25628): Drinks
I need these values to List array, like
List<String> data = {"Country", "Meals", "Drinks"};
and it shows in
Widget _text() {
return Column(
children: <Widget>[
Text(data[0]),
Text(data[1]),
Text(data[2])
],
);
}

List<Widget> data = [];
void getData() {
Firestore.instance
.collection(collectionName)
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
String text = '${f.data}'.split(":")[0].substring(1);
data.add(Text(text));
});
});
}
Widget _text() {
return Column(
children: data,
);
}

Related

flutter SingleChildScrollView remove item

I have the following code where I generate a list of items(data is taken from Firebase). I would like to implement a functionality to remove items but I don't know how to access the list and how to remove items:
class _MyOfferState extends State<MyOffer> {
List<Widget> items = [];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
...
body: SingleChildScrollView(
child: Column(
children: [
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('Offers')
builder: (BuildContext context, snapshot) {
snapshot.data.docs.forEach((element) {
element.get('items').forEach((item) {
String _name = element['name'];
String _category = item['category'];
items.add(offer(name, category, context,...));
});
}
);
}
return new Column(
children: List.unmodifiable(() sync* {
yield* items;
}()),
);
},
),
}
}
This is a dynamic class where I have GestureDetector. The item should be deleted when a user clicks on the it.
dynamic offer(name, category, context,) {
return GestureDetector(
child: Container(
child: Row(
children: [
Text(name),
Text(category),
],
),
),
),
onTap: () {
// remove item should be here
},
);
}
Removing the offer from within itself is not the best practice but you can accomplish it in a number of ways. The first I can think of is to pass a function that removes it when creating the offer like this:
items.add(offer(name, category, context,..., () {
setState(() {
FirebaseFirestore.instance
.collection('Offers')
.doc(element['id'])
.delete();
items.remoev(index);
});
}));
You'll need to create the index beforehand and increase it each time but I don't recommend doing it.
The way I would done do this is change the offer to be:
dynamic offer(name, category, context,) {
return Container(
child: Row(
children: [
Text(name),
Text(category),
],
),
);
}
And when creating the offer wrap it in the GestureDetector like this:
items.add(GestureDetector(
child: offer(name, category, context,...)),
onTap: () {
setState(() {
FirebaseFirestore.instance
.collection('Offers')
.doc(element['id'])
.delete();
items.remoev(index);
});
},
);
You'll have to do the same thing with the index but I consider it a better approach since the child has no power over the parent and can't change its state which is a good practice.
you need to pass index of item and delete by index:
int index = 0;
snapshot.data.docs.forEach((element) {
element.get('items').forEach((item) {
String _name = element['name'];
String _category = item['category'];
items.add(offer(index, name, category, context,...));
index++;
});
Widget offer(int index, string name, string category, BuildContext context,) {
return GestureDetector(
child: Container(
child: Row(
children: [
Text(name),
Text(category),
],
),
),
),
onTap: () {
// remove item should be here
items.removeAt(index);
setState((){});
},
);
}
}
);
}
return new Column(
children: List.unmodifiable(() sync* {
yield* items;
}()),
);
Your list is getting build by Stream data the one you provided to your StreamBuilder, do create new list you need to change Stream value, I suggest to keep FirebaseFirestore.instance.collection('Offers') instance in a stream and modify the stream.
class _MyOfferState extends State<MyOffer> {
List<Widget> items = [];
StreamController _controller = StreamController();
#override
void initState() {
super.initState();
_controller.addStream( FirebaseFirestore.instance
.collection('Offers').snapshots());
}
// dont forgot to close stream
#override
void dispose() {
_controller.close();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
...
body: SingleChildScrollView(
child: Column(
children: [
StreamBuilder<QuerySnapshot>(
stream: _controller.stream,
builder: (BuildContext context, snapshot) {
snapshot.data.docs.forEach((element) {
element.get('items').forEach((item) {
String _name = element['name'];
String _category = item['category'];
items.add(offer(name, category, context,(){
// remove function is here
snapshot.data.docs.removeWhere((e) => e.id == element.id);
_controller.add(snapshot.data);
});
});
}
);
}
return new Column(
children: List.unmodifiable(() sync* {
yield* items;
}()),
);
},
),
}
}
Also pass onTap to your widget function
dynamic offer(name, category, context, onTap) {
return GestureDetector(
child: Container(
child: Row(
children: [
Text(name),
Text(category),
],
),
),
),
onTap: onTap,
);
}

Flutter I want to rebuild the list but can't be assigned

I want to pull the database in Flutter and list it with dynamic checkboxes as well, but I get an error. I was told to rebuild the list by referring to these links.
https://github.com/tekartik/sqflite/issues/140
But two errors have occurred. error: The argument type 'Future<List<Map<dynamic, dynamic>>>' can't be assigned to the parameter type 'Iterable'. and error: A value of type 'List' can't be assigned to a variable of type 'Future'.
class Classname extends StatefulWidget {
Classname({Key key}) : super(key: key);
#override
createState() => _ClassnameState();
}
class _ClassnameState extends State<Classname> {
String test;
String test2;
String test3;
bool isChecked = false;
Future _data;
#override
void initState() {
_data = List.from(getData());
super.initState();
}
Future<List<Map>> getData() async {
String path = join(await getDatabasesPath(), 'dbname.db');
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE tablename(id INTEGER PRIMARY KEY, test TEXT, test2 TEXT, test3 TEXT)");
});
List<Map> result = await database.rawQuery('SELECT * FROM tablename');
return result;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Map>>(
future: _data,
builder: (context, result) {
      if (result.connectionState == ConnectionState.waiting) {
return Center(
child:
CircularProgressIndicator());
}
if (!result.hasData) {
return Center(
child: Text(
'no data'),
);
}
return SingleChildScrollView(
child: Container(
child: Column(
children: List.generate(result.data.length, (index) {
var data = result.data[index];
test = data['test'];
test2 = data['test2'];
test3 = data['test3'];
data.putIfAbsent('isChecked', () => false);
return Column(
children: [
Row(
children: <Widget>[
Checkbox(
value: data['isChecked'],
onChanged: (bool value) {
setState(() {
data['isChecked'] = value;
});
},
),
Container(
child: Text(
test,
),
),
Container(
child: Text(test2),
),
],
),
Align(
alignment: Alignment.centerLeft,
child: Text(
test3,
),
),
],
);
}),
),
),
);
},
),
);
}
}
So I also tried changing the definition of the variable like Future<List<Map>> _data and so on but errors have occured. In the above case, error: A value of type 'List' can't be assigned to a variable of type 'Future<List<Map<String, dynamic>>>'. and error: The argument type 'Future<List<Map<dynamic, dynamic>>>' can't be assigned to the parameter type 'Iterable'.
Please tell how to resolve.
The two errors are occured in this line:
_data = List.from(getData());
The argument type 'Future<List<Map<dynamic, dynamic>>>' can't be assigned to the parameter type 'Iterable'
The named factory constructor List.of(...)'s first param require a Iterable, but in your case, getData() is a Future, so the error occured.
A value of type 'List' can't be assigned to a variable of type 'Future<List<Map<String, dynamic>>>'
The _data field in your case is declared as Future, but it is assigned with a List, so the error occured.
To resolve them, don't use List.of. getData() is a Future, and _data just need it.
#override
void initState() {
super.initState();
_data = getData();
}
And another way is that use result list. Remove FutureBuilder and change Future _data to List _data, and assign it's value in getData with result.
List _data;
#override
void initState() {
super.initState();
getData();
}
Future<void> getData() async {
String path = join(await getDatabasesPath(), 'dbname.db');
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE tablename(id INTEGER PRIMARY KEY, test TEXT, test2 TEXT, test3 TEXT)");
});
List<Map> result = await database.rawQuery('SELECT * FROM tablename');
setState((){
_data = result;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _data == null
? CircularProgressIndicator()
: _data.isEmpty()
? Center(child: Text('no data'))
: SingleChildScrollView(),
);
}

Quicker way to implement into a list?

Im making a list of radio buttons. But cant figure a way to map them. The current method making one by one which is too much and with 10+ radio buttons this is taking up hundreds of lines of code.
enum SingingCharacter {char1, char2, char3, char4}
class _HomeScreenState extends State<HomeScreen> {
SingingCharacter _character = SingingCharacter.char1;
final List myList= ['One','Two','Thre' ];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Container(
child: Column(children: <Widget>[
RadioListTile<SingingCharacter>(
title: Text('${myList[0]}'),
value: SingingCharacter.char1,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
RadioListTile<SingingCharacter>(
title: Text('${myList[1]}'),
value: SingingCharacter.char2,
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
)
....
]),
));
}
}
Any method to loop through this and show in children?
Thanks
You could change your List to a Map and then use this to map your enum values to Widgets. Like this (disclaimer: Code not tested, but something like this should be possible):
enum SingingCharacter {char1, char2, char3}
class _HomeScreenState extends State<HomeScreen> {
SingingCharacter _character = SingingCharacter.char1;
final Map<SingingCharacter, String> radioMap = {SingingCharacter.char1: 'One', SingingCharacter.char2: 'Two', SingingCharacter.char3: 'Three'};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Container(
child: Column(
children: _generateRadioButtons()
),
)
);
}
List<Widget> _generateRadioButtons() {
return SingingCharacter.values.map((char) {
return RadioListTile<SingingCharacter>(
title: Text('${radioMap[char]}'),
value: char
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
);
}).toList();
}
}
You can take advantage of the spread operator and unwrap directly a for loop on your Column.
final List myList= ['One','Two','Thre' ];
return Column(children: [
for (int i = 0; i < myList.length; i++)
RadioListTile<SingingCharacter>(
title: Text(myList[i]),
value: SingingCharacter.values[i],
groupValue: _character,
onChanged: (SingingCharacter value) {
setState(() {
_character = value;
});
},
),
]);

Cache two Lists in flutter

I want to cache two lists that got from Firebase to use to later when the user is offline
This is the full code for my list display screen -
import 'package:flutter/material.dart';
import 'package:naamaa/calculations/name-list-calc.dart';
List namesList = List();
List meaningsList = List();
class NameList extends StatefulWidget {
#override
_NameListState createState() => _NameListState();
}
class _NameListState extends State<NameList> {
Future<String> getPosts() async {
var names = await NameListCalc().nameListCalc();
namesList.addAll(names[0]);
meaningsList.addAll(names[1]);
String s = 'test';
return s;
}
#override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: getPosts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
resizeToAvoidBottomPadding: false,
body: ListView.builder(
padding: EdgeInsets.zero,
itemBuilder: (context, position) {
return Row(
children: <Widget>[
Container(
width: 100,
child: Text(namesList[position]),
),
Container(
child: Text(meaningsList[position]),
)
],
);
},
itemCount: namesList.length,
),
);
} else {
return Text(':(');
}
},
);
}
}
I want to cache namesList and meaningsList for later use.
If someone can help it would be great :)
I didn't get complete requirement by your question description but you can use shared_preferences library to store the data list as following
Add following line pubspec.yaml
dependencies:
flutter:
sdk: flutter
shared_preferences:
You can use this example and add more utility methods as per you requirement.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
AppConfig.init(() {
runApp(MyApp());
});
}
class CustomModel {
int id;
String name;
CustomModel({this.id, this.name});
factory CustomModel.fromJson(Map<String, dynamic> json) {
return CustomModel(id: json["id"], name: json["name"]);
}
Map<String, dynamic> toJson() => {"id": id, "name": name};
#override
String toString() {
return "id: $id, name: $name";
}
}
class AppConfig {
static Future init(VoidCallback callback) async {
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferenceUtils.init();
callback();
}
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class SharedPreferenceUtils {
static SharedPreferences prefs;
static init() async {
prefs = await SharedPreferences.getInstance();
// storing lists
await putStringList("m_list", ["abc", "def"]);
await putObjectList("data",
[CustomModel(id: 1, name: "Bob"), CustomModel(id: 2, name: "Alice")]);
}
static Future<bool> putStringList(String key, List<String> list) async {
return prefs.setStringList(key, list);
}
static List<String> getStringList(String key) {
return prefs.getStringList(key);
}
static Future<bool> putObjectList(String key, List<Object> list) async {
if (prefs == null) return null;
List<String> _dataList = list?.map((value) {
return json.encode(value);
})?.toList();
return prefs.setStringList(key, _dataList);
}
static List<T> getObjList<T>(String key, T f(Map v),
{List<T> defValue = const []}) {
if (prefs == null) return null;
List<Map> dataList = getObjectList(key);
List<T> list = dataList?.map((value) {
return f(value);
})?.toList();
return list ?? defValue;
}
static List<Map> getObjectList(String key) {
if (prefs == null) return null;
List<String> dataList = prefs.getStringList(key);
return dataList?.map((value) {
Map _dataMap = json.decode(value);
return _dataMap;
})?.toList();
}
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(SharedPreferenceUtils.getStringList("m_list").toString()),
Text(SharedPreferenceUtils.getObjList<CustomModel>(
"data", (v) => CustomModel.fromJson(v)).toString()),
],
),
),
),
);
}
}
You don't need to store the lists in init() as it's done for this example. You can also pass data from one widget to others in multiple ways and if you are looking for state management then you can use BLOC or providers.

Flutter: `notifyListeners` not updating the list

I am trying to list categories of products in my app, and i am using provider package for state management. During the build time its shows the list is empty even though it is not, then I add a click event to update the list that time it works.
I call the getAllCategories() function during the splash screen and the vallCategoryList has values.
This is my category class
class Category with ChangeNotifier{
int catId;
String catName;
String catThumbnail;
List<SetCategory> allCategoryList = [];
void getAllCategories() async {
String categoryUrl = 'https://app.ecwid.com/api/ccccccc';
Response allCategory = await get(categoryUrl);
print('getAllCategories');
if (allCategory.statusCode == 200) {
var categoryData = allCategory.body;
int totalcount = jsonDecode(categoryData)['count'];
if (allCategoryList.length != totalcount) {
allCategoryList.clear();
for (int i = 0; i < totalcount; i++) {
allCategoryList.add(SetCategory(
catId: jsonDecode(categoryData)['items'][i]['id'],
catName: jsonDecode(categoryData)['items'][i]['name'],
catThumbnail: jsonDecode(categoryData)['items'][i]['thumbnailUrl'],
));
}
}
}
print('allcategorylist length ${allCategoryList.length}');
notifyListeners();
}
}
class SetCategory {
int catId;
String catName;
String catThumbnail;
SetCategory(
{ this.catId, this.catName, this.catThumbnail});
}
My code for screen
class HomeScreen extends StatefulWidget {
static const String id = 'homeScreen';
// static int reload = 0;
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
final category = Provider.of<Category>(context);
print('category length ${category.allCategoryList.length}'); // here it shows length as 0 even though it has a value of 16.
return Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Category ${category.allCategoryList.length}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
textAlign: TextAlign.start,
),
),
InkWell(
onTap: () {
category.getAllCategories(); // when i tap here this updates the list
}),
],
),
Did you use ChangeNotifierProvider in your Widget as shown here
If you just used Provider it is not updating but just makes the object accessible from the descendants
Solved by adding a Consumer, changed code like this
child: Consumer<Category>(
builder: (_,category,__){
return ListView.builder();
}