How to pass data down the widget tree? - flutter

I have read and understood a similar question posted here, but am having trouble applying it to my use case. I am new to Flutter and am creating an app that streams audio from a given URL using Ryan Heise's audio_service plugin. Using this plugin I instantiate an audioHandler immediately upon starting my app:
late AudioHandler audioHandler;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.music());
audioHandler = await AudioService.init(
builder: () => AudioPlayerHandler(),
config: const AudioServiceConfig(
androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
androidNotificationChannelName: 'Channel Name',
androidNotificationOngoing: true,
),
);
runApp(const MyApp());
}
With this audioHandler initialized, I would like to use it in child widgets. The example below demonstrates one such child widget:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Koradi Radio",
theme: ThemeData(
brightness: Brightness.light,
scaffoldBackgroundColor: Colors.white70,
),
darkTheme: ThemeData(
brightness: Brightness.dark,
),
themeMode: ThemeMode.system,
home: const EnglishHome());
}
}
class EnglishHome extends StatefulWidget {
const EnglishHome({Key? key}) : super(key: key);
#override
_EnglishHomeState createState() => _EnglishHomeState();
}
class _EnglishHomeState extends State<EnglishHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('English Radio'),
backgroundColor: Colors.transparent,
),
body: ...
}
}
Note that MyApp currently just routes to EnglishHome(), but I plan on adding additional languages and instead routing MyApp to a page where a user can select their language. How can I pass audioHandler to all descendent widgets from Main() ? (EnglishHome, EspHome, FrenchHome, etc?) Based upon what I have read, I will either be modifying the Key parameter of child widgets or else their BuildContext?

You can use provider package and all you need to do is use Provider.value and then use Provider.of(context) in your EnglishHome, FrenchHome etc classes.
late AudioHandler audioHandler;
Future<void> main() async {
audioHandler = await AudioService.init(...);
runApp(MyApp(audioHandler));
}
class MyApp extends StatelessWidget {
final AudioHandler audioHandler;
const MyApp(this.audioHandler, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Provider.value(
value: audioHandler, // Providing the data above MaterialApp
child: MaterialApp(
home: EnglishHome(),
),
);
}
}
class EnglishHome extends StatelessWidget {
#override
Widget build(BuildContext context) {
// Accessing the data.
final audioHandler = Provider.of<AudioHandler>(context);
return Container();
}
}

The other answers here are also valid solutions, but what I was able to do was add an audioHandler parameter to EnglishHome:
class EnglishHome extends StatefulWidget {
var audioHandler;
EnglishHome({Key? key, this.audioHandler}) : super(key: key);
#override
_EnglishHomeState createState() => _EnglishHomeState();
And then pass the audioHandler in when the Widget was called from my main.dart file:
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Radio",
theme: ThemeData(
brightness: Brightness.light,
scaffoldBackgroundColor: Colors.blue[100],
),
darkTheme: ThemeData(
brightness: Brightness.dark,
),
themeMode: ThemeMode.system,
home: EnglishHome(
audioHandler: audioHandler,
));
}
}

Related

Flutter app resizing on different devices

I installed my app on 2 different devices, the problem is both devices show different widget sizes. Both devices have different screen sizes.
The expected result ->
image1 from Moto One Fusion+
image2 from OnePlus 6pro
main.dart code ->
void main() {
runApp(BmiApp());
}
class BmiApp extends StatelessWidget {
const BmiApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/input': (context) => InputPage(),
'/calculate': (context) => CalculatedResult(),
},
theme: ThemeData.dark().copyWith(
appBarTheme: AppBarTheme(
color: Color(0xFF0A1234),
),
scaffoldBackgroundColor: Color(0xFF0A1234),
),
initialRoute: '/input',
);
}
}
input_page.dart code ->
class InputPage extends StatefulWidget {
const InputPage({Key? key}) : super(key: key);
#override
State<InputPage> createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text('BMI Calculator'),
centerTitle: true,
),
body:Column(),
),
);
}
}
Inside column I have stacked all the widgets.
Github link for complete code

Flutter Get.changeTheme() does not change the app theme (misuse?)

Here described the simplest/lasiest way to change a color theme of the app. It states:
Please do not use any higher level widget than GetMaterialApp in order to update it.
It appears my understanding of how to use the Get package is not correct.
Tried 2 variants of the code (with or without the commented out line) - the theme does not change.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'ThemeDemo',
// UPDATE: Added 2 lines
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: Get.isDarkMode ? ThemeMode.light : ThemeMode.dark,
home: const MyHomePage(
title: 'Theme Demo',
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
PopupMenuButton<String>(
onSelected: handleClick,
itemBuilder: (BuildContext context) {
return {'Logout', 'Theme'}.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
),
],
),
);
}
void handleClick(String value) {
switch (value) {
case 'Logout':
break;
case 'Theme':
// UPDATE: Uncommented the control
Get.changeTheme(Get.isDarkMode ? ThemeData.light() : ThemeData.dark());
break;
}
}
}
Please, help me to understand the problem and how to use Get to change the theme.
I am very beginner in Flutter, so any constructive critics is welcome!
you should specify the Theme and darkTheme in GetMaterialApp then the themeMode,
like this:
GetMaterialApp(
// your other properties
theme: YourDefaultTHemeHere,
darkTheme: YourDarkThemeHere,
themeMode: Get.isDarkMode ? ThemeMode.light : ThemeMode.dark,
)

what is the alternative for accentColor Flutter

I'm new to flutter. working on a chat app. I have created a app bar but the colors I added in main.dart not display. it just display as default blue color. how to correct??
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(
debugShowCheckedModeBanner: false,
//title: 'Profile Section',
theme: ThemeData(
primaryColor: Color(0xff075e54),
accentColor: Color(0xff128C7E)),
home: Homescreen(key: null),
);
}
}
homescreen.dart
import 'package:flutter/material.dart';
class Homescreen extends StatefulWidget {
Homescreen({ Key? key }) : super(key: key);
#override
_HomescreenState createState() => _HomescreenState();
}
class _HomescreenState extends State<Homescreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Whatsapp Clone"),
actions: [
IconButton(icon: Icon(Icons.search), onPressed: () {}),
IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
],
),
);
}
}
Use this, as your code. It should work.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
final ThemeData theme = ThemeData(); //You need to make a var, that works as ThemeData
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
//title: 'Profile Section',
theme: theme.copyWith(
colorScheme: theme.colorScheme.copyWith(primary: Color(0xff075e54),secondary: Color(0xff128C7E), //Then use it with colorScheme.
),
),
home: Homescreen(key: null),
);
}
}

Splash screen with auto route

I want to implement an animated splash screen
Generally in MaterialApp, we have a property called home but when I use autoroute (MaterialApp.router) am unable to find a home in it then how can I implement a splash screen with autoroute
package link
main.dart file
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
runApp(
EasyLocalization(
supportedLocales: const <Locale>[Locale('en')],
path: 'assets/i18n',
fallbackLocale: const Locale('en'),
child: const App(),
),
);
}
class Appp extends StatefulWidget {
const Appp({Key? key}) : super(key: key);
#override
State<Appp> createState() =>
_ApppState();
}
class _ApppState extends State<Appp> {
final _themeStore = ThemeStore();
final _appRouter = AppRouter();
#override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
title: 'App',
theme: _themeStore.selectedThemeData,
routerDelegate: _appRouter.delegate(),
routeInformationParser: _appRouter.defaultRouteParser(),
);
}
}
First You have to show the Splash screen and then for the next screen, you can use MaterialApp.router
eg.
void main() {
runApp(SplashScreen());
}
class SplashScreen extends StatelessWidget {
SplashScreen({Key? key}) : super(key: key);
final _appRouter = AppRouter();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Splash App',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: AnimatedSplashScreen(
animationDuration: const Duration(seconds: 2),
splashTransition: SplashTransition.slideTransition,
splash: Icons.code,
nextScreen: MaterialApp.router(
routeInformationParser: _appRouter.defaultRouteParser(),
routerDelegate: _appRouter.delegate(),
),
),
);
}
}
Packages Used:
auto route
animated_splash_screen

changing theme through button input in Flutter

I made a button, and when that button is pressed, I want to change the color of the theme.
I am trying to modify the color with the value received from the button, but it does not work.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
String themeColors=context.watch<DisplayList>().themeColor;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.${themeColors}, //How do I fix this part?
),
Or is there another way to change the color?
themeColors variable already contains a string of the color to be changed.
You can't actually have a syntax like this one on Flutter: Colors.${themeColors}
To handle multiples themes, you need to create multiples ThemeData and switch them with a ValueNotifier.
I suggest you to use an already made community package like theme_provider which will help you to switch between themes very easily.
You will have to convert your widget to Stateful and use the setState method
class XYZ extends StatefulWidget {
const XYZ({Key? key}) : super(key: key);
#override
_XYZState createState() => _XYZState();
}
class _XYZState extends State<XYZ> {
var myAppBarThemeColor = Colors.red;
#override
Widget build(BuildContext context) {
print(myAppBarThemeColor);
return MaterialApp(
theme: ThemeData(appBarTheme: AppBarTheme(backgroundColor: myAppBarThemeColor)),
home: Scaffold(
appBar: AppBar(
title: Text('Hello'),
),
body: Center(
child: TextButton(
onPressed: () => setState(() => myAppBarThemeColor = Colors.green),
child: Text('Change AppBar Color'),
),
),
),
);
}
}
You can use findAncestorStateOfType to manage the state of the root widget.
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
static _AppState? of(BuildContext context) => context.findAncestorStateOfType<_AppState>();
#override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
late bool isDarkMode;
late ThemeModeStorage storage;
void toggleDarkMode() {
setState(() {
isDarkMode = !isDarkMode;
});
storage.writeBool(value: isDarkMode);
}
...
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeConfig(isDarkMode).themeData,
home: HomeScreen(),
);
}
}
So you can call this everywhere in your app.
App.of(context)?.toggleDarkMode();