I am having an issue where when I am using my toggle button and need to go in between different classes it turns back off. I wrote up a simple example below of a simple text button that takes you to and from the start page and when you return the toggle is set to false still for some reason. Thanks for all the help in advance!
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
),
home: const TestButton(),
);
}
}
class TestButton extends StatefulWidget {
const TestButton({Key? key}) : super(key: key);
@override
_TestButtonState createState() => _TestButtonState();
}
class _TestButtonState extends State<TestButton> {
List<bool> _selections = List.generate(1, (index) => false);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Container(
child: ToggleButtons(
children: [
Icon(Icons.volume_off),
],
isSelected: _selections,
onPressed: (int index) {
setState(() {
_selections[index] = !_selections[index];
});
},
),
),
Container(
child: TextButton(
child: Text('Press To navigate to different screen'),
onPressed: () => Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => SecondScreen(),
),
),
),
)
],
),
);
}
}
class SecondScreen extends StatefulWidget {
const SecondScreen({Key? key}) : super(key: key);
@override
_SecondScreenState createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: TextButton(
child: Text('Go to first page'),
onPressed: () => Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => TestButton(),
),
), ),
),
);
}
}
you need to save your state and re-fetch it when user comebacks to that specific page. you can handle it with two approaches:
global.dart
file and temporarily save state in a boolean or any data type there and then use it in your initState
!SharedPreferences
to store that state for all times.