how to disable ui build when setchanged method in flutter - android

I have a graph view my app, whenever my function works it's also rebuilding
how to control my UI
var response = await getdashboarddata(tokenkey);
setState(() {
});

use FutureBuilder
Widget projectWidget() {
return FutureBuilder(
builder: (context, projectSnap) {
if (projectSnap.connectionState == ConnectionState.none &&
projectSnap.hasData == null) {
//print('project snapshot data is: ${projectSnap.data}');
return Container();
}
return ListView.builder(
itemCount: projectSnap.data.length,
itemBuilder: (context, index) {
ProjectModel project = projectSnap.data[index];
return Column(
children: <Widget>[
// Widget to display the list of project
],
);
},
);
},
future: getdashboarddata(tokenkey),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('ProjectList'),
),
body: projectWidget(),
);
}

Related

how can use future in the listview flutter?

I have future function and I want show this in the listview.seprator, but the listview do not get the future value. how can i fix this?
this is my code:
my hive class:
#HiveType(typeId: 3)
class TaskCat extends HiveObject{
#HiveField(0)
String catName;
#HiveField(1)
int userId;
#HiveField(2)
User? user;
TaskCat(this.catName,this.user,this.userId);
}
This is my function:
Future<List> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
and this is my listview code:
FutureBuilder(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
Future<List> test = controller.showCategoryInHome();
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: 11 , // here currently I set the fix value but I want the length of my list
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
test[index].[catName], // and here not working too bucouse the list is future
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
},
)
Try this:
FutureBuilder<List>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount:data.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {},
child: Text(
data[index]['catName'],
style: normalTextForCategory,
),
);
},
separatorBuilder: (BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
}
}
},
),
Inside your Future you have builder, where you can access to your future when it ready via snapshot.
I've added the precise type where to make the use of Futurebuilder easier.
Future<List<TaskCat>> showCategoryInHome() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var taskCatBox = await Hive.openBox('taskCat');
var filtertaskCat = taskCatBox.values
.where(
(TaskCat) => TaskCat.userId == sharedPreferences.getInt('key'))
.toList();
return filtertaskCat;
}
And adjust your Futurebuilder to the following:
FutureBuilder<List<TaskCat>>(
future: controller.showCategoryInHome(),
builder: (context, snapshot) {
// Check if your future has finished
if(snapshot.hasData) {
// Here you have the result of your future, which is a List<TaskCat>
final tasks = snapshot.data;
return ListView.separated(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: tasks.length,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
},
child: Text(
tasks[index].catName,
style: normalTextForCategory,
),
);
},
separatorBuilder:
(BuildContext context, int index) {
return const VerticalDivider(
width: 15,
color: Colors.transparent,
);
},
);
} else {
// Here you can show e.g. a CircularProgressIndicator
return SizedBox();
}
},
)

How Can i get only this text? Without " DocumentReference<Map<String, dynamic>> "

enter image description here
enter image description here
``
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Scaffold(
appBar: AppBar(automaticallyImplyLeading: false),
backgroundColor: Colors.black,
body: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection('History').doc(userId).snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
final DocumentSnapshot<Map<String, dynamic>>? getDocument = snapshot.data;
final Map<String, dynamic>? map = getDocument?.data();
var setList = map!['userchat'];
return ListView.builder(
itemCount: setList.length,
itemBuilder: (context, index) {
final get = setList[index];
print(get);
return const Text('data');
},
);
}
return const Text('data');
},
),
),
);
}
``
For getting the required text, i.e., the text in index = 3, you can use a conditional check in itemBuilder.
if(index==3){
final get = setList[index];
print(get);
return const Text('data');
}else{
return const SizedBox.shrink();
}
SizedBox.shrink() helps in avoiding to return a null value, but in turn returns a widget which doesn't show up, or simply nothing.
You can use it if you want, or can go with Text('data').

i can't access uid from firebase

I can't access uid from firebase. I tried so many times. can anyone help me with this issue?
class Massages extends StatelessWidget {
#override Widget build(BuildContext context) {
return FutureBuilder(
future: Future.value(FirebaseAuth.instance.currentUser),
builder: (ctx, futureSnapshot) {
if (futureSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chat')
.orderBy('createdAt', descending: true)
.snapshots(),
builder: (ctx, AsyncSnapshot<dynamic> chatSnapshot) {
if (chatSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
reverse: true,
itemCount: chatSnapshot.data!.docs.length,
itemBuilder: (ctx, index) => MessageBubble(
chatSnapshot.data!.docs[index]['text'],
chatSnapshot.data!.docs[index]['userId'] ==
futureSnapshot.data?.uid,
key: ValueKey(chatSnapshot.data!.documentID),
),
);
});
}); } }
It looks like futureSnapshot.data returns an Object rather than a User. You could try casting it to the correct type with:
((User)futureSnapshot.data)?.uid,

flutter_blue project is not working even the example project,and snapshot data is returning an empty array?

I am using ubuntu other projects can be excuted most of the bluetooth functionalities are not working.
The snapshot.data is always an empty array even though there are so many active devices and I am using vs code ubuntu and flutter_blue package. I tested it on many devices and its not working even the example they gave is not working.
Is the problem with my ubuntu system or someone else has the problem with the same example they have on git ?
https://github.com/pauldemarco/flutter_blue
class FindDevicesScreen extends StatefulWidget {
FindDevicesScreen({Key key}) : super(key: key);
#override
_FindDevicesScreenState createState() => _FindDevicesScreenState();
}
class _FindDevicesScreenState extends State<FindDevicesScreen> {
#override
void initState() {
// TODO: implement initState
super.initState();
FlutterBlue.instance.startScan(timeout: Duration(seconds: 4));
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
RaisedButton(
onPressed: () {
FlutterBlue.instance.startScan(timeout: Duration(seconds: 4));
},
child: Text("Search"),
),
StreamBuilder<List<BluetoothDevice>>(
stream: Stream.periodic(Duration(seconds: 2))
.asyncMap((_) => FlutterBlue.instance.connectedDevices),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
print('connection active');
}
if (snapshot.hasData) {
return Column(children: [
Text("There is data"),
Text(snapshot.data.length.toString())
]);
} else if (snapshot.hasError) {
print("Error");
return Center(
child: Text("There is some error"),
);
} else {
return Center(
child: Text("Nodata"),
);
}
}),
Divider(),
StreamBuilder<List<ScanResult>>(
stream: FlutterBlue.instance.scanResults,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("inside checking");
print(snapshot.data);
return Text(snapshot.data.length.toString());
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else {
return Text("No data");
}
}),
],
)),
);
}
}

Flutter ListView into ListView.builder

I want to convert this ListView into a ListView.builder, because i need the Index. Can someone show me how to cnvert thsi ListView?`Thank for your Help :)
return new ListView(
children: snapshot.data.documents.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['name']),
);
}).toList(),
);
Here is how you can create a ListView builder, which provides an index
var documents = snapshot.data.documents.map((DocumentSnapshot document);
return ListView.builder(
itemCount: documents.length,
itemBuilder: (context, index) => {
// Just an example, use your own fields
Text(documents[index].Name);
});
You just provide a builder function. This function gets called for each Item in your data. The amount of items you set with itemCount.
Example:
var dataList = []; //this would be your snapshot data
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(gallery),
),
body: ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text(dataList[index]),
),
),
);
}

Categories

Resources