How to pop only the circular progress indicator in flutter? - android

'''buildShowDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext cont1) {
return Center(
child: LoadingAnimationWidget.threeArchedCircle(
color: Colors.white, size: 50),
);
});
}
loginFunction(http.Client client, jsonBody) async {
buildShowDialog(context);
var url = Uri.parse("https://my-office-timesheet.herokuapp.com/api/signin");
var respsonse = await client.post(url, body: jsonBody);
if (respsonse.statusCode == 200) {
Navigator.of(context).pop();
if (this.mounted) {
setState(() {
jsonResponse = Post.fromJson(json.decode(respsonse.body));
});
}
if (jsonResponse!.success == true) {
if (this.mounted) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) => Dashboard()),
(Route<dynamic> route) => false);
//this code is to route without a back button.
}
} else {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text("Message:"),
content: Text("${jsonResponse?.message}"),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(ctx).pop();
if (this.mounted) {
setState(() {
jsonResponse = null;
});
}
},
child: const Text("Ok"),
),
],
),
);
}
}
return respsonse;
}'''
List view builder
ListView.builder(
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _fieldNames.length,
itemBuilder: (context, index) {
return Column(
children: [
FieldBuilderForm(
key: ValueKey(index),
fieldColor: _fieldColor[index],
fieldTextColor: _fieldTextColor[index],
fieldName: _fieldNames[index],
controller: controller[index],
size: displaySize,
),
In the above code when I pop the LoadingAnimationWidget. The list view builder which I made is the one popping instead. Any suggestions?

Related

how can i fix this error of my todo list?

I have made an to do list with firebase. but when i click to create a new to do, i can't see anything apear on my page but in firebase it does show the string.
How can i fix this
(this is in flutter)
logcat:
2022-10-19 15:24:50.758 23369-23584 flutter com.example.voorbeeld I apen created
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class video_info extends StatefulWidget {
#override
_video_infoState createState() => _video_infoState();
}
class _video_infoState extends State<video_info> {
String todoTitle = "";
createTodos() {
DocumentReference documentReference =
FirebaseFirestore.instance.collection("MyTodos").doc(todoTitle);
//Map
Map<String, String> todos = {"todoTitle": todoTitle};
documentReference.set(todos).whenComplete(() {
print("$todoTitle created");
});
}
deleteTodos(item) {
DocumentReference documentReference =
FirebaseFirestore.instance.collection("MyTodos").doc(item);
documentReference.delete().whenComplete(() {
print("$item deleted");
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("mytodos"),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
title: Text("Add Todolist"),
content: TextField(
onChanged: (String value) {
todoTitle = value;
},
),
actions: <Widget>[
TextButton(
onPressed:() {
createTodos();
Navigator.of(context).pop();
},
child: Text("Add"))
],
);
});
},
child: Icon(
Icons.add,
color: Colors.white,
),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection("Mytodos").snapshots(),
builder: (context, snapshots) {
if (snapshots.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshots.data?.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot =
snapshots.data!.docs[index];
return Dismissible(
onDismissed: (direction) {
deleteTodos(documentSnapshot["todoTitle"]);
},
key: Key(documentSnapshot["todoTitle"]),
child: Card(
elevation: 4,
margin: EdgeInsets.all(8),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
child: ListTile(
title: Text(documentSnapshot["todoTitle"]),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red,
),
onPressed: () {
deleteTodos(documentSnapshot["todoTitle"]);
}),
),
));
});
} else {
return Align(
alignment: FractionalOffset.bottomCenter,
child: CircularProgressIndicator(),
);
}
}),
);
}}
also does anyone know a link to an tuturial where they explain how i can link the database to a user login.
You're using another collection.
You are adding your todo to this collection:
FirebaseFirestore.instance.collection("MyTodos")
But in your StreamBuilder you use the collection "Mytodos":
stream: FirebaseFirestore.instance.collection("Mytodos").snapshots(),
Try creating a stream variable on state class
late final myStream = FirebaseFirestore.instance.collection("MyTodos").snapshots();
#override
Widget build(BuildContext context) {
....
body: StreamBuilder(
stream: myStream

How to add automatic scroll to a StreamBuilder Listview in flutter

I asked this question and got the accurate answer
It worked fine, then I tried wrapping it to StreamBuilder as seen below, it stopped working
StreamBuilder<List<WinsModel>>(
stream: WinController().readWins(),
builder: (context, snapshot2) {
if (snapshot2.hasError) {
return NoData(
text: "Error: 947474774", title: "");
} else if (snapshot2.hasData) {
final testi = snapshot2.data!;
return ListView.builder(
controller: _controller,
key: itemKey,
itemCount: testi.length,
itemBuilder: (BuildContext context, index) {
return ListTile(
title: SmallText(
text: testi[index].body,
color: Colors.white,
size: FDiamension.getSize(16),
isBold: true,
),
);
},
);
} else {
return Container();
}
}),
Please which way to add automatic scroll to a StreamBuilder Listview
Put this
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (_controller.hasClients) {
_controller.animateTo(_controller.position.maxScrollExtent,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut);
}
});
after
} else if (snapshot2.hasData) {
Like
StreamBuilder<List<WinsModel>>(
stream: WinController().readWins(),
builder: (context, snapshot2) {
if (snapshot2.hasError) {
return NoData(
text: "Error: 947474774", title: "");
} else if (snapshot2.hasData) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (_controller.hasClients) {
_controller.animateTo(_controller.position.maxScrollExtent,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut);
}
});
final testi = snapshot2.data!;
return ListView.builder(
controller: _controller,
key: itemKey,
itemCount: testi.length,
itemBuilder: (BuildContext context, index) {
return ListTile(
title: SmallText(
text: testi[index].body,
color: Colors.white,
size: FDiamension.getSize(16),
isBold: true,
),
);
},
);
} else {
return Container();
}
}),

How to put item from Dart Flutter Secure Storage stringList into listTile?

I have a listTile. I want to place the items from the stringList that I pulled from Secure Storage to the listTile. How can I do it?
Future<void> listUpload() async {
final prefences = await SharedPreferences.getInstance();
final getTests = prefences.getStringList("tests"); // get item
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
child: ListTile(
// title: item
),
),
);
},
),
);
}
Here is the function for loading data from the Secure Storage:
Future<List<String?>> listUpload() async {
final prefences = await SharedPreferences.getInstance();
final getTests = prefences.getStringList("tests"); // get item
return Future.value(getTests);
}
You must use FutureBuilder like that:
// some page of your app
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Expanded(
child: FutureBuilder(
future: listUpload(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
late List<String?> items;
if (snapshot.connectionState == ConnectionState.waiting) {
// here is what should be shown if the
// data from the SharedPreferences has not yet been loaded
items = [];
} else if (snapshot.connectionState == ConnectionState.done &&
snapshot.hasData) {
// here is a case when items
// from SharedPreferences has been loaded
items = snapshot.data as List<String?>;
} else {
// other cases:
items = [];
}
// Now we can build ListView
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
child: ListTile(
title: Text(
items[index].toString()
)),
),
);
},
);
})),
),
);
}
}
you just have to wrap your text list elements in a Text widget:
Future<void> listUpload() async {
final prefences = await SharedPreferences.getInstance();
final getTests = prefences.getStringList("tests"); // get item
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
child: ListTile(
title: Text(getTests[index])
),
),
);
},
),
);
}

Flutter: How to show loading screen after the url is added?

I'm building a URL shortner app. I want to show a loading screen after the url is entered. This is my code. I'm a beginner to flutter. Please help me since this is my first app. The code is given below. As you can see the I'm using FutureBuilder so if the url list is empty it shows a corresponding message but I want it to disappear after the ok button of the alertdialog is pressed.
class _homePageState extends State<homePage> {
List userURL = List();
List item = List();
Future<List> getdata() async {
//JSON Parser
var url = 'https://api.shrtco.de/v2/shorten?url=${userURL.last}';
var respons = await http.get(url);
var result = jsonDecode(respons.body);
item.add(result['result']['short_link']); //dictionary parse
print(item);
return item;
}
createAlertDialog(BuildContext context) {
//method for alertdialog
//promise to return string
TextEditingController customController =
TextEditingController(); //new texteditingc object
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter URL: "),
content: TextField(
controller: customController,
),
actions: [
MaterialButton(
elevation: 5.0,
child: Text("OK"),
onPressed: () {
if (customController.text != null &&
customController.text != "") {
userURL.add(customController.text);
}
setState(() {});
Navigator.of(context).pop();
},
)
],
);
});
}
#override
Widget build(BuildContext context) {
String temp;
return Scaffold(
appBar: AppBar(
title: Text("Shortie"),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: getdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.sentiment_very_dissatisfied,
color: Colors.grey,
size: 80,
),
Text(
"No short links to display",
style: TextStyle(
color: Colors.grey[700],
fontSize: 15,
//fontWeight: FontWeight.bold
),
),
]));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(Icons.link),
title: Text(snapshot.data[index]),
subtitle: Text(userURL[index]),
onTap: () {
Share.share(
'Check out the short link I just shared with the application Shortie: ${snapshot.data[index]}',
subject: 'Shortie short link');
print(snapshot.data[index]);
},
);
},
);
}
},
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
createAlertDialog(context).then((onValue) {
temp = onValue;
print(temp);
});
You can make use of the connection state class of the FutureBuilder as follows:
FutureBuilder(
future: getdata(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(backgroundColor: Colors.blue);
} else {
return Container();
}
},
);
Also, on your button you need to call setState() to trigger the view reload, which in turn will again check the connectionState, if the async function is still in progress you will see the loading indicator, otherwise something you put in else

Flutter - Update sibling Widget after calling setState() in one

I have a Dialog Widget, there are a Button and Text field there. On pressing the button there is a function which setState() and variable change. I do not see these changes instantly on a screen in the text field, I need to close and open Dialog again. Why and how can I make it happen (so the whole class/parent will be rebuilt? (It is about "Get location" button and next field)
class MyDialog extends StatefulWidget {
MyDialogState createState() => MyDialogState();
}
class MyDialogState extends State<MyDialog> {
String userLocation;
double sleepLength;
#override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)
),
elevation: 20,
child: ListView(
children: <Widget>[
FlatButton(
child: Text("Get location $userLocation"),
onPressed: () {
final Geolocator geolocator = Geolocator();
geolocator
.getCurrentPosition()
.then((Position position) async {
List<Placemark> place = await geolocator
.placemarkFromCoordinates(position.latitude, position.longitude);
Placemark p = place[0];
setState(() {
//userLocation = "${p.locality}, ${p.country}";
userLocation = Random().nextInt(10).toString();
print("A");
});
}).catchError((e) {
print("------------");
print(e);
print("------------");
});
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$userLocation"))
),
Divider(),
FlatButton(
child: Text("Set sleep length"),
onPressed: () {
//TODO
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$sleepLength"))
),
Divider(),
],
)
);
}
);
},
child: Icon(
Icons.settings
),
backgroundColor: Colors.black12,
);
}
}
In my case StatefulBuilder works.
StatefulBuilder is best used in situations where you have a medium/large widget tree and state needs to be introduced for a small subsection of that tree.
wrap you child with StatefulBuilder hope it helps..
Using StatefulBuilder you can solve this problem
Replace your MyDialogState with:
class MyDialogState extends State<MyDialog> {
String userLocation;
double sleepLength;
#override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)
),
elevation: 20,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return ListView(
children: <Widget>[
FlatButton(
child: Text("Get location $userLocation"),
onPressed: () {
final Geolocator geolocator = Geolocator();
geolocator
.getCurrentPosition()
.then((Position position) async {
List<Placemark> place = await geolocator
.placemarkFromCoordinates(position.latitude, position.longitude);
Placemark p = place[0];
setState(() {
//userLocation = "${p.locality}, ${p.country}";
userLocation = Random().nextInt(10).toString();
print("A");
});
}).catchError((e) {
print("------------");
print(e);
print("------------");
});
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$userLocation"))
),
Divider(),
FlatButton(
child: Text("Set sleep length"),
onPressed: () {
//TODO
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$sleepLength"))
),
Divider(),
],
);
},
)
);
}
);
},
child: Icon(
Icons.settings
),
backgroundColor: Colors.black12,
);
}
}
You have to wrap Dialog with return StatefulBuilder builder: ...
and carefully about } and ); because in this case it is a long string
code snippet
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Dialog(
...
);
},
);
your code with StatefulBuilder
class MyDialog extends StatefulWidget {
MyDialogState createState() => MyDialogState();
}
class MyDialogState extends State<MyDialog> {
String userLocation;
double sleepLength;
#override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
elevation: 20,
child: ListView(
children: <Widget>[
FlatButton(
child: Text("Get location $userLocation"),
onPressed: () {
final Geolocator geolocator = Geolocator();
geolocator
.getCurrentPosition()
.then((Position position) async {
List<Placemark> place =
await geolocator.placemarkFromCoordinates(
position.latitude, position.longitude);
Placemark p = place[0];
setState(() {
//userLocation = "${p.locality}, ${p.country}";
userLocation = Random().nextInt(10).toString();
print("A");
});
}).catchError((e) {
print("------------");
print(e);
print("------------");
});
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$userLocation"))),
Divider(),
FlatButton(
child: Text("Set sleep length"),
onPressed: () {
//TODO
},
),
Padding(
padding: EdgeInsets.all(10),
child: Center(child: Text("$sleepLength"))),
Divider(),
],
));
});
});
},
child: Icon(Icons.settings),
backgroundColor: Colors.black12,
);
}
}

Categories

Resources