Using useState() and useEffect() in Flutter with flutter_hooks can significantly simplify state management and lifecycle handling in your Flutter apps. These hooks, inspired by React hooks, enable you to use state and other React features in a functional-style component approach.
Understanding useState() in Flutter Hooks
useState()
is a hook that lets you add state to a stateless widget. When you use useState()
, it returns a variable and a function to update that variable. This is similar to the useState
hook in React. The state persists across widget rebuilds, but it’s scoped to the current widget instance, so each instance has its own state.
Understanding useEffect() in Flutter Hooks
useEffect()
is used for side effects in functional components. It is the equivalent of componentDidMount
, componentDidUpdate
, and componentWillUnmount
in React class components. useEffect()
takes two arguments: a callback function and a list of dependencies. The callback function runs after the widget build is complete. If the dependencies change, the callback function is called again. Learn more about useEffect() here.
Example: Creating a Dummy Loading Page with Mock API Call
In this example, we’ll create a simple Flutter application using flutter_hooks
that shows a loading screen and simulates an API call.
First, add flutter_hooks
to your pubspec.yaml
file:
dependencies:
flutter_hooks: ^latest_version
Now, let’s create the main widget using useState() and useEffect():
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LoadingPage(),
);
}
}
class LoadingPage extends HookWidget {
@override
Widget build(BuildContext context) {
final isLoading = useState(true);
useEffect(() {
Future.delayed(Duration(seconds: 3), () {
isLoading.value = false;
});
return null; // This is the cleanup function, not needed in this case.
}, const []); // Empty dependency array means this runs once.
return Scaffold(
body: Center(
child: isLoading.value
? CircularProgressIndicator()
: Text('Loaded!'),
),
);
}
}
In this example, we’ve created a LoadingPage
widget that uses useState()
to manage the loading state and useEffect()
to simulate an API call. The useEffect()
hook is used to change the loading state after a delay of 3 seconds, mimicking a network request. When the state changes, the widget rebuilds, and the CircularProgressIndicator
is replaced with a Text
widget indicating that the content is loaded.
This approach is a clean and efficient way to handle state and side effects in your Flutter applications using functional components.
Subscribe to our email newsletter to get the latest posts delivered right to your email.
Comments