Я бы сказал, что общие предпочтения могут быть одним из подходов к достижению этого.
После некоторых усилий я придумал следующий пример кода:
main.dart
SharedPreferences prefs;
String theme;
void main() async {
prefs = await SharedPreferences.getInstance();
// just for checking purpose
if (prefs.getString("theme") == null) {
await prefs.setString("theme", "darkTheme");
}
theme = (prefs.getString("theme") != null) ? "darkTheme" : "lightTheme";
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp(theme: theme));
}
class MyApp extends StatelessWidget {
final theme;
const MyApp({Key key, this.theme}) : super(key: key);
@override
Widget build(BuildContext context) {
Brightness themeData =
theme == "darkTheme" ? Brightness.dark : Brightness.light;
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(brightness: themeData),
home: theme == "darkTheme"
? Scaffold(
body: Center(
child: Container(
child: Text("Dark Theme"),
),
),
)
: Scaffold(
body: Center(
child: Container(
child: Text("Light Theme"),
),
),
),
debugShowCheckedModeBanner: false,
);
}
}
MainActivity.kt
import android.content.Context
import android.content.SharedPreferences
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
var sharedPreferences: SharedPreferences =
getSharedPreferences("FlutterSharedPreferences", 0)
private val theme: String? = sharedPreferences.getString("flutter." + "theme", "lightTheme")
override fun setTheme(resid: Int) {
super.setTheme(resid)
if (theme == "darkTheme") {
application.setTheme(R.style.LaunchTheme)
}
if (theme == "lightTheme") {
application.setTheme(R.style.NormalTheme)
}
}
}
стилей. xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowEnableSplitTouch">false</item>
<item name="android:splitMotionEvents">false</item>
<item name="android:windowBackground">@android:color/black</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@android:color/white</item>
<item name="android:windowEnableSplitTouch">false</item>
<item name="android:splitMotionEvents">false</item>
</style>
</resources>
К вашему сведению: - В конечном итоге Flutter сохраняет значение в собственном общем предпочтении. Формат получения данных другой.
Android:
var sharedPreferences: SharedPreferences =
getSharedPreferences("FlutterSharedPreferences", 0)
private val theme: String? = sharedPreferences.getString("flutter." + "theme", "lightTheme")
IOS:
if let name = NSUserDefaults.standard.string(forKey: "flutter.test") {
print(name)
}
Артикул: - ios, android
Этот код у меня работает. :)