Prevent FutureBuilder recalling future function every build - flutter

How to prevent FutureBuilder future function to be recalled on every build? In below case, the category.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Future<List<Category>> categories =
CategoryRepository().getCategories();
#override
Widget build(BuildContext context) {
return Center(
child: FutureBuilder(
future: categories,
builder: (BuildContext context, AsyncSnapshot<List<Category>> snapshot) {
if (snapshot.hasData) {
return SomeWidget()
} else {
return OtherWidget();
}
}
)
);
}
}
In the documentation, to prevent that, the future should be obtained before, i.e. initState(). I have tried to move the assignment of the categories to the initState() function. But the function still called when state change / rebuild.
class _HomeScreenState extends State<HomeScreen> {
late Future<List<Category>> categories;
#override
void initState() {
categories = CategoryRepository().getCategories();
super.initState();
}
}

Did you try this way -
class _HomeScreenState extends State<HomeScreen> {
Future<List<Category>> categories;
#override
void initState() {
if(categories==null) categories = CategoryRepository().getCategories();
super.initState();
}
}

Related

Null check operator error when trying to read Passed variable in Constructor

I'm trying to read value passed from a Stateful object to another Stateful object. I've defined a simple String variable, and trying to read the value in the constructor.
It's showing error: Null check operator used on a null value.
But when I try to read the value in the widget, it works, and doesn't show any error.
Here is the main.dart
void main() {
runApp(MaterialApp(
home: HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var dummyText = "Dummy Text";
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => DPage(dummyText)));
},
child: Text('Press Me!'),
),
));
}
}
Here is the DPage where I'm trying to read variable dummyText.
class DPage extends StatefulWidget {
var dvariable;
DPage(this.dvariable);
#override
State<DPage> createState() => _DPageState();
}
class _DPageState extends State<DPage> {
_DPageState() {
print(widget.dvariable);
}
#override
Widget build(BuildContext context) {
return Container(child: Text(widget.dvariable));
}
}
if I comment the following line, which is in constructor -
print(widget.dvariable);
It runs without any problem. But if I try to access the widget.dvariable in the constructor, it throws error -
Null check operator used on a null value
How do I access this dvariable or value of "dummyText" in constructor? Any pointers will be greatly appreciated.
Note: I'm noob in dart/flutter.
You can use initState for this case. Constructor gets called before initState State and not ready to read widget class variables.
#override
void initState() {
super.initState();
print(widget.dvariable);
}
class DPage extends StatefulWidget {
var dvariable;
DPage(this.dvariable);
#override
State<DPage> createState() => _DPageState();
}
class _DPageState extends State<DPage> {
#override
void initState() {
super.initState();
print(widget.dvariable);
}
#override
Widget build(BuildContext context) {
return Container(child: Text(widget.dvariable));
}
}
Or
class DPage extends StatefulWidget {
var dvariable;
DPage(this.dvariable);
#override
State<DPage> createState() => _DPageState();
}
class _DPageState extends State<DPage> {
_DPageState() {
print(widget.dvariable);
}
#override
void initState() {
super.initState();
_DPageState();
}
#override
Widget build(BuildContext context) {
return Container(child: Text(widget.dvariable));
}
}

Flutter Do not show FutureBuilder error screen

I use the package flutter_native_splash to display a splash screen. During this time, I want to instantiate a Future and, when it's done, I want to remove the splash screen and build a widget thanks to a FutureBuilder. The problem is that the device displays the splash screen AND the ErrorScreen for few milliseconds (I don't want it) before building the widget.
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Metadata> futureMetadata;
#override
void initState() {
super.initState();
initialization();
}
void initialization() async {
futureMetadata = fetchMetadata();
FlutterNativeSplash.remove();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder<Metadata>(
future: futureMetadata,
builder: (BuildContext context, AsyncSnapshot<Metadata> snapshot) {
if (snapshot.hasData) {
return NavBar(data: snapshot.data);
} else {
return const ErrorScreen();
}
}
)
);
}
}
FlutterNativeSplash.remove(); removes the splash screen.
because you want to remove the splashscreen after it's finished loading I think you want instead of
futureMetadata = fetchMetadata();
FlutterNativeSplash.remove();
do
futureMetadata = fetchMetadata();
await futureMetadata;
FlutterNativeSplash.remove();

Hive Box not updating after clearing in other dart file/class

i am clearing a hive box and updating it in the very next line.
The update can be seen in the same file code (through debugging).
But somehow for the other stateless widget/class/file box is empty.
boxT.clear() ;
setState(() {
boxT.addAll({
[count2, totalEntries]
});});
Reason for clearing the box on everytime a specific button is pressed: I am adding a map. addAll() simply creates another entry. i dont want it. i have also tried put and putall but they are only showing the value and not the key.
That's because Hive is NOT a state management tool, if you add/remove something to/from your box, you need to let your state know. You should have a global state that listens to changes from that Box.
Example with a ValueNotifier.
class ItemsNotifier extends ValueNotifier<List<Item>> {
ItemsNotifier() : super(getItemsFromBox());
List<Item> _items = getItemsFromBox();
#override
List<Item> get value => _items;
void addItem(Item item) {
addItemToBox(item);
_items = getItemsFromBox();
notifyListeners();
}
Future<void> deleteAll() async {
await clearBox();
_items = getItemsFromBox();
notifyListeners();
}
}
List<Item> getItemsFromBox() {
return Hive.box<Item>('items').values.toList();
}
Future<void> addItemToBox(Item item) async {
await Hive.box<Item>('items').add(item);
}
Future<void> clearBox() async {
await Hive.box<Item>('items').clear();
}
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
late final ItemsNotifier _notifier;
#override
void initState() {
_notifier = ItemsNotifier();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ExampleWidget(notifier: _notifier),
floatingActionButton: FloatingActionButton(
onPressed: _notifier.deleteAll,
child: const Icon(Icons.delete),
),
);
}
#override
void dispose() {
_notifier.dispose();
super.dispose();
}
}
class ExampleWidget extends StatelessWidget {
const ExampleWidget({required this.notifier, Key? key}) : super(key: key);
final ItemsNotifier notifier;
#override
Widget build(BuildContext context) {
return ValueListenableBuilder<List<Item>>(
valueListenable: notifier,
builder: (context, items, _) {
return ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text(items[index].title),
),
itemCount: items.length,
);
},
);
}
}
Note that if you have multiple pages using the data from this box, I would recommend using something like Provider and having a ChangeNotifier instead of the ValueNotifier or using flutter_bloc and having a Repository that handles communication with Hive.

How to listen changes inside TextController?

I am using GetX. I need to listen changes in TextController. The follow code do not work:
class Controller extends GetxController{
final txtList = TextEditingController().obs;
#override
void onInit() {
debounce(txtList, (_) {
print("debouce$_");
}, time: Duration(seconds: 1));
super.onInit();
}
}
Is does not print nothing when I am changing txtList value from UI. I suppose it's because it does not check text field inside txtList.
How to get it work?
You need to pass an RxInterface into debounce to do this via GetX. Just create an RxString and add a listener to the controller then pass the RxString into debounce.
class Controller extends GetxController {
final txtList = TextEditingController();
RxString controllerText = ''.obs;
#override
void onInit() {
txtList.addListener(() {
controllerText.value = txtList.text;
});
debounce(controllerText, (_) {
print("debouce$_");
}, time: Duration(seconds: 1));
super.onInit();
}
}
Then on any page in the app you can pass in that controller into the textfield and it'll print the value after the user stops typing for 1 second.
class Home extends StatelessWidget {
final controller = Get.put(Controller());
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextField(controller: controller.txtList), // this will print
),
);
}
}
And if you need that value for anything else it's also always accessible via controller.controllerText.value.
By TextEditingController.text, we can already get changing text input value so it does not need .obs.
To pass parameter for debounce, we should pass value itself : txtList.text. (see here: https://github.com/jonataslaw/getx/blob/master/documentation/en_US/state_management.md)
final txtList = TextEditingController(); // 1. here
#override
void onInit() {
debounce(txtList.text, (_) { // 2. here
print("debouce$_");
}, time: Duration(seconds: 1));
super.onInit();
}
This might work.
=================== added 11/21 ==================
Here's the example. I know the RxString variable seems a duplication for TextEditingController.text, but GetX's debounce function needs RxString type variable as a parameter. I tried to find more elegant way to do this, but I couldn't find anything. Please let me know if somebody knows a better way.
// in controller
late final TextEditingController textController;
final RxString userInput = "".obs;
#override
void onInit() {
super.onInit();
textController = TextEditingController();
userInput.value = textController.text;
textController.addListener(() {
userInput.value = textController.text;
}
);
debounce(userInput, (_) {
print("debouce$_");
}, time: Duration(seconds: 1));
}
check this snippet for example to listen to TextEditingController text change listener
import 'package:flutter/material.dart';
void main() async {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(),
darkTheme: ThemeData.dark(),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final TextEditingController controller = TextEditingController();
#override
void initState() {
super.initState();
controller.addListener(_printLatestValue);
}
void _printLatestValue() {
print('Second text field: ${controller.text}');
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: TextField(
controller: controller,
),
);
}
}

Passing Data to a Stateful Widget in Flutter

I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.
The two styles I've seen are:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState(_server);
}
class _ServerInfoState extends State<ServerInfo> {
Server _server;
_ServerInfoState(Server server) {
this._server = server;
}
}
This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.
The other method is to use widget._server:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState();
}
class _ServerInfoState extends State<ServerInfo> {
#override
Widget build(BuildContext context) {
widget._server = "10"; // Do something we the server value
return null;
}
}
This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.
Is there a best practice for this?
Don't pass parameters to State using it's constructor.
You should only access the parameters using this.widget.myField.
Not only editing the constructor requires a lot of manual work ; it doesn't bring anything. There's no reason to duplicate all the fields of Widget.
EDIT :
Here's an example:
class ServerIpText extends StatefulWidget {
final String serverIP;
const ServerIpText ({ Key? key, this.serverIP }): super(key: key);
#override
_ServerIpTextState createState() => _ServerIpTextState();
}
class _ServerIpTextState extends State<ServerIpText> {
#override
Widget build(BuildContext context) {
return Text(widget.serverIP);
}
}
class AnotherClass extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: ServerIpText(serverIP: "127.0.0.1")
);
}
}
Best way is don't pass parameters to State class using it's constructor. You can easily access in State class using widget.myField.
For Example
class UserData extends StatefulWidget {
final String clientName;
final int clientID;
const UserData(this.clientName,this.clientID);
#override
UserDataState createState() => UserDataState();
}
class UserDataState extends State<UserData> {
#override
Widget build(BuildContext context) {
// Here you direct access using widget
return Text(widget.clientName);
}
}
Pass your data when you Navigate screen :
Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserData("WonderClientName",132)));
Another answer, building on #RĂ©miRousselet's anwser and for #user6638204's question, if you want to pass initial values and still be able to update them in the state later:
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}
class _MyStatefulState extends State<MyStateful> {
String foo;
_MyStatefulState({this.foo});
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
For passing initial values (without passing anything to the constructor)
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState();
}
class _MyStatefulState extends State<MyStateful> {
#override
void initState(){
super.initState();
// you can use this.widget.foo here
}
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
Flutter's stateful widgets API is kinda awkward: storing data in Widget in order to access it in build() method which resides in State object đŸ¤¦ If you don't want to use some of bigger state management options (Provider, BLoC), use flutter_hooks (https://pub.dev/packages/flutter_hooks) - it is a nicer and cleaner substitute for SatefullWidgets:
class Counter extends HookWidget {
final int _initialCount;
Counter(this._initialCount = 0);
#override
Widget build(BuildContext context) {
final counter = useState(_initialCount);
return GestureDetector(
// automatically triggers a rebuild of Counter widget
onTap: () => counter.value++,
child: Text(counter.value.toString()),
);
}
}
#RĂ©mi Rousselet, #Sanjayrajsinh, #Daksh Shah is also better. but I am also defined this is in from starting point.that which parameter is which value
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
String name = "Flutter Demo";
String description = "This is Demo Application";
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainActivity(
appName: name,
appDescription: description,
),
);
}
}
class MainActivity extends StatefulWidget {
MainActivity({Key key, this.appName, this.appDescription}) : super(key: key);
var appName;
var appDescription;
#override
_MainActivityState createState() => _MainActivityState();
}
class _MainActivityState extends State<MainActivity> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.appName),
),
body: Scaffold(
body: Center(
child: Text(widget.appDescription),
),
),
);
}
}
The best practice is to define the stateful widget class as immutable which means defining all dependencies (arrival parameter) as final parameters. and getting access to them by widget.<fieldName> in the state class. In case you want to change their values like reassigning you should define the same typed properties in your state class and re-assign them in the initState function. it is highly recommended not to define any not-final property in your stateful widget class and make it a mutable class. something like this pattern:
class SomePage extends StatefulWidget{
final String? value;
SomePage({this.value});
#override
State<SomePage> createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> {
String? _value;
#override
void initState(){
super.initState();
setState(() {
_value = widget.value;
});
}
#override
Widget build(BuildContext context) {
return Text(_value);
}
}
To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data.
class PageTwo extends StatefulWidget {
final String title;
final String name;
PageTwo ({ this.title, this.name });
#override
PageTwoState createState() => PageTwoState();
}
class PageTwoStateState extends State<PageTwo> {
#override
Widget build(BuildContext context) {
return Text(
widget.title,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w700),
),
}
}
class PageOne extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialButton(
text: "Open PageTwo",
onPressed: () {
var destination = ServicePage(
title: '<Page Title>',
provider: '<Page Name>',
);
Navigator.push(context,
MaterialPageRoute(builder: (context) => destination));
},);
}
}