Flutter statefulBuilder widget saves app performance and makes it faster. Some expensive operations could be replaced with this.
StatefulBuilder works with a callback function. This callback function triggers rebuild.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.amber,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
int count = 0;
return Scaffold(
appBar: AppBar(title: const Text('StatefulBuilder')),
body: Padding(
padding: const EdgeInsets.all(30),
child: Center(
child: Column(
children: [
StatefulBuilder(builder: (context, myStateFunc){
return Column(
children: [
Container(
width: 300,height: 300,
decoration: const BoxDecoration(
color: Colors.red, shape: BoxShape.circle),
child: Center(
child: Text(
count.toString(),
style: const TextStyle(fontSize: 80, color: Colors.white),
),
),
),
const SizedBox(height: 20),
ElevatedButton.icon(
onPressed: () {
// Call setInnerState function
myStateFunc(()=>count++);
},
icon: const Icon(Icons.add),
label: const Text('Increase By One')),
],
);
}),
const SizedBox(height: 100,),
const ElevatedButton(onPressed: null, child: Text("Not rebuild widget"))
],
),
),
),
);
}
}