【发布时间】:2021-06-08 08:04:13
【问题描述】:
如何根据用户选择的选项更新图像图标。该变量需要存储在 shared_preferences 中。我试过这段代码,但它不工作。请告诉我我哪里错了?当用户在选择选项后导航返回时,主屏幕需要立即更改。
homePage.dart
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String selection;
@override
void initState() {
getType();
super.initState();
}
getType() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
selection = prefs.getString('type');
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context){
return SelectionType();
}));
},
child: Text("Select Type")
),
Container(
height: 100,
width: 100,
child: displayImageChoice(),
)
],
),
);
}
displayImageChoice() {
switch(selection){
case 'Mango':
return Icon(Icons.ac_unit);
break;
case 'Apple':
return Icon(Icons.backpack_outlined);
break;
case 'Banana':
return Icon(Icons.offline_bolt);
break;
}
}
}
selectionType.dart
import 'package:flutter/material.dart';
import 'package:saving_data_shared/optionSelector.dart';
import 'package:saving_data_shared/selectionPref.dart';
enum type {Mango, Apple, Banana}
class SelectionType extends StatefulWidget {
@override
_SelectionTypeState createState() => _SelectionTypeState();
}
class _SelectionTypeState extends State<SelectionType> {
type selectionType = type.Mango;
bool isSelected = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
OptionSelectorBar(
elementDisplayText: 'Mango',
isSelected:
selectionType == type.Mango,
onTap: () async {
setState(() {
selectionType = type.Mango;
});
TypePrefs.setTypePrefs('Mango');
},
),
OptionSelectorBar(
elementDisplayText: 'Apple',
isSelected: selectionType == type.Apple,
onTap: () async {
setState(() {
selectionType = type.Apple;
});
TypePrefs.setTypePrefs('Apple');
},
),
OptionSelectorBar(
elementDisplayText: 'Banana',
isSelected: selectionType == type.Banana,
onTap: () async {
setState(() {
selectionType = type.Banana;
});
TypePrefs.setTypePrefs('Banana');
},
),
],
),
);
}
}
sharedpref.dart
import 'package:shared_preferences/shared_preferences.dart';
class TypePrefs {
static Future<String> getTypePrefs() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('typePref');
}
static Future<bool> setTypePrefs(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString('type', value);
}
}
【问题讨论】:
标签: flutter sharedpreferences flutter-dependencies