I am trying to use ScreenUtil() to make my text font size responsive.
This line caused an error "ScreenUtil.init(context);".
And the error is "MediaQuery.of() called with a context that does not contain a MediaQuery."
Widget build(BuildContext context) {
ScreenUtil.init(context);
return MaterialApp(
title: 'Meals App',
theme: ThemeData(
primarySwatch: Colors.pink,
accentColor: Colors.amber,
canvasColor: Color.fromRGBO(255, 254, 229, 1),
fontFamily: 'Raleway',
textTheme: TextTheme(
headline6: TextStyle(
fontSize: ScreenUtil().setSp(100),
fontFamily: 'RobotoCondensed',
fontWeight: FontWeight.bold,
),
bodyText1: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
bodyText2: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
),
),
home: TabsScreen(favouriteMeals),
);
}
You can copy paste run full code below
You can use builder of MaterialApp
code snippet
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
builder: (context, widget) {
ScreenUtil.init(context,
width: 750, height: 1334, allowFontScaling: false);
return widget;
},
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
working demo
full code
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
void main() => runApp(MyApp());
class TextStyles {
TextStyle t1 = TextStyle(fontSize: 24.ssp, color: Colors.black);
TextStyle t2 = TextStyle(fontSize: 24.sp, color: Colors.black);
}
var ts = TextStyles();
class TextStyle2 {
static TextStyle2 ts2;
factory TextStyle2() {
if (ts2 == null) {
ts2 = TextStyle2();
}
return ts2;
}
TextStyle t1 = TextStyle(fontSize: 24.ssp, color: Colors.black);
TextStyle t2 = TextStyle(fontSize: 24.sp, color: Colors.black);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
builder: (context, widget) {
ScreenUtil.init(context,
width: 750, height: 1334, allowFontScaling: false);
return widget;
},
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
//Set the fit size (fill in the screen size of the device in the design) If the design is based on the size of the iPhone6 (iPhone6 750*1334)
//ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);
return ExampleWidget(title: 'FlutterScreenUtil Demo');
}
}
class ExampleWidget extends StatefulWidget {
const ExampleWidget({Key key, this.title}) : super(key: key);
final String title;
#override
_ExampleWidgetState createState() => _ExampleWidgetState();
}
class _ExampleWidgetState extends State<ExampleWidget> {
#override
Widget build(BuildContext context) {
printScreenInformation();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: 375.w,
height: 200.h,
color: Colors.red,
child: Text(
'My width:${375.w}dp \n'
'My height:${200.h}dp',
style: TextStyle(
color: Colors.white, fontSize: ScreenUtil().setSp(24)),
),
),
Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(10)),
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
color: Colors.blue,
child: Text(
'My width:${0.5.wp}dp \n'
'My height:${ScreenUtil().setHeight(200)}dp',
style: TextStyle(
color: Colors.white,
fontSize: ScreenUtil().setSp(24))),
),
],
),
Text('Device width:${ScreenUtil.screenWidthPx}px'),
Text('Device height:${ScreenUtil.screenHeightPx}px'),
Text('Device width:${ScreenUtil.screenWidth}dp'),
Text('Device height:${ScreenUtil.screenHeight}dp'),
Text('Device pixel density:${ScreenUtil.pixelRatio}'),
Text('Bottom safe zone distance:${ScreenUtil.bottomBarHeight}dp'),
Text('Status bar height:${ScreenUtil.statusBarHeight}dp'),
Text(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}',
textAlign: TextAlign.center,
),
Text(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}',
textAlign: TextAlign.center,
),
SizedBox(
height: ScreenUtil().setHeight(100),
),
Text('System font scaling factor:${ScreenUtil.textScaleFactor}'),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'My font size is 24px on the design draft and will not change with the system.',
style: TextStyle(
color: Colors.black,
fontSize: 24.sp,
)),
Text(
'My font size is 24px on the design draft and will change with the system.',
style: ts.t1),
],
)
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.title),
onPressed: () {
ScreenUtil.init(context,
width: 1500, height: 1334, allowFontScaling: false);
setState(() {});
},
),
);
}
void printScreenInformation() {
print('Device width dp:${ScreenUtil.screenWidth}'); //Device width
print('Device height dp:${ScreenUtil.screenHeight}'); //Device height
print(
'Device pixel density:${ScreenUtil.pixelRatio}'); //Device pixel density
print(
'Bottom safe zone distance dp:${ScreenUtil.bottomBarHeight}'); //Bottom safe zone distance,suitable for buttons with full screen
print(
'Status bar height px:${ScreenUtil.statusBarHeight}dp'); //Status bar height , Notch will be higher Unit px
print(
'Ratio of actual width dp to design draft px:${ScreenUtil().scaleWidth}');
print(
'Ratio of actual height dp to design draft px:${ScreenUtil().scaleHeight}');
print(
'The ratio of font and width to the size of the design:${ScreenUtil().scaleWidth * ScreenUtil.pixelRatio}');
print(
'The ratio of height width to the size of the design:${ScreenUtil().scaleHeight * ScreenUtil.pixelRatio}');
print('System font scaling:${ScreenUtil.textScaleFactor}');
print('0.5 times the screen width:${0.5.wp}');
print('0.5 times the screen height:${0.5.hp}');
}
}
Please try this.
Widget build(BuildContext context) {
return Builder(builder:(ctx){
ScreenUtil.init(ctx);
return MaterialApp(
title: 'Meals App',
theme: ThemeData(
primarySwatch: Colors.pink,
accentColor: Colors.amber,
canvasColor: Color.fromRGBO(255, 254, 229, 1),
fontFamily: 'Raleway',
textTheme: TextTheme(
headline6: TextStyle(
fontSize: ScreenUtil().setSp(100),
fontFamily: 'RobotoCondensed',
fontWeight: FontWeight.bold,
),
bodyText1: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
bodyText2: TextStyle(color: Color.fromRGBO(20, 51, 51, 1)),
),
),
home: TabsScreen(favouriteMeals),
);});
}
This will introduce a new context with a new MediaQuery
if you just want to migrate slowly screens one by one or just for specific widget you can try this.
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
ScreenUtil.init(
constraints,
allowFontScaling: false,
designSize: Size(1080, 300),
);
return Scaffold(
backgroundColor: Color(0xFFFCBDE9),
resizeToAvoidBottomInset: false,
body: Column(
children: [
_buildAppBar(context),
],
),
);
},
);
}
You are welcome to use the screenutil plug-in, see that there is a problem with your usage
ScreenUtil.init should be used in the subcomponents of MaterialApp。
like this:
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Module',
builder: FlutterBoost.init(postPush: _onRoutePushed),
home: EmptyPage());
}
·······
class EmptyPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
ScreenUtil.init(context, width: 320, height: 568, allowFontScaling: false);
return Scaffold(
body: Container(),
);
}
}
If you want to use it outside , you can use v4.
https://pub.flutter-io.cn/packages/flutter_screenutil/versions/4.0.0-beta2
Please read the document carefully
Related
You can see a black area around the elevated button in the given image. I want to change it and match it with the background color of the rest of the page which is Colors.grey[350] .
The flow is like this => in the main.dart I am calling the widget onboardingscreen and then displaying it with pageview.builder
The code for Main.Dart
import 'package:my_mythology/Pages/login_page.dart';
import 'package:my_mythology/Pages/on_boarding_screen.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
backgroundColor: Colors.grey,
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
),
home:
Column(
children: [
Expanded(
child: PageView.builder(
itemBuilder: (context,index) =>(
Onboarding_Screen(
image: "asset/odin1.png",
title: "Learn Mythology In a Fun Way",
description:
"What's your favorite story? Mythology is full of them! Discover one of the most interesting subjects ever, including gods and goddesses, monsters and heroes. Knowledge is power, so never stop learning. From the classics to the newest stories, it's all free in My Mythology!",
)
)
),
),
Row(
children: [
SizedBox( height: 60,
width: 60,
child: ElevatedButton(onPressed: () {},
style: ElevatedButton.styleFrom(shape: CircleBorder(),),
child: SvgPicture.asset("asset/forwardarrow.svg",fit: BoxFit.contain,),)),
],
),
],
),
);
}
}
the code for Onboardingscreen is
// ignore: camel_case_types
class Onboarding_Screen extends StatelessWidget {
final String image, title, description;
const Onboarding_Screen({
Key? key,
required this.description,
required this.image,
required this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.grey[350],
body: SafeArea(
child: Column(
children: [
Spacer(),
SizedBox(
height: 400,
width: 400,
child: Image.asset(
image,
fit: BoxFit.fill,
)),
Text(title,
style: Theme.of(context).textTheme.headline5!.copyWith(
fontWeight: FontWeight.bold, color: Colors.black)),
Spacer(),
Text(
description,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black54, fontSize: 16),
),
Spacer(),
],
)),
),
);
}
}
``
First add a Scaffold to your screen, then specify a background color.
import 'package:flutter/material.dart';
import 'onboarding.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
backgroundColor: Colors.grey,
),
home: Scaffold(
backgroundColor: Colors.grey[350],
body: Column(
children: [
Expanded(
child: PageView.builder(
itemBuilder: (context, index) => (const Onboarding_Screen(
image: "asset/odin1.png",
title: "Learn Mythology In a Fun Way",
description:
"What's your favorite story? Mythology is full of them! Discover one of the most interesting subjects ever, including gods and goddesses, monsters and heroes. Knowledge is power, so never stop learning. From the classics to the newest stories, it's all free in My Mythology!",
)),
)),
Row(
children: [
SizedBox(
height: 60,
width: 60,
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
),
child: null,
),
),
],
),
],
),
),
);
}
}
Here is the result.
You are using scaffold inside Onboarding_Screen, therefore the outer part is missing material. You dont need to use multiple MaterialApp and use Scaffold on top level as route widget.
Mostly, you will need to follow
MaterialApp(
home: Scaffold (
body: Column(...
If you create second page, means visit using navigator , you need to use Scaffold, but not MaterialApp.
You can directly provide scaffoldBackgroundColor on MaterialApp's theme.
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
scaffoldBackgroundColor: Colors.grey[350], /// direct here
),
home: Scaffold(
body: Column(
children: [
Expanded(
Your widget will
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
scaffoldBackgroundColor: Colors.grey[350], /// direct here
),
home: Scaffold(
body: Column(
children: [
Expanded(
child: PageView.builder(
itemBuilder: (context, index) => (Onboarding_Screen(
image: "asset/odin1.png",
title: "Learn Mythology In a Fun Way",
description:
"What's your favorite story? Mythology is full of them! Discover one of the most interesting subjects ever, including gods and goddesses, monsters and heroes. Knowledge is power, so never stop learning. From the classics to the newest stories, it's all free in My Mythology!",
))),
),
Row(
children: [
SizedBox(
height: 60,
width: 60,
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
),
child: Text("fff")
// SvgPicture.asset(
// "asset/forwardarrow.svg",
// fit: BoxFit.contain,
// ),
)),
],
),
],
),
),
);
}
}
class Onboarding_Screen extends StatelessWidget {
final String image, title, description;
const Onboarding_Screen({
Key? key,
required this.description,
required this.image,
required this.title,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
children: [
Spacer(),
SizedBox(
height: 400,
width: 400,
child: Image.asset(
image,
fit: BoxFit.fill,
)),
Text(
title,
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(fontWeight: FontWeight.bold, color: Colors.black),
),
Spacer(),
Text(
description,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black54, fontSize: 16),
),
Spacer(),
],
),
);
}
}
This black background is due to the fact that Row widget with ElevatedButton is not wrapped in Scaffold. Try this in this main.dart:
import 'package:my_mythology/Pages/login_page.dart';
import 'package:my_mythology/Pages/on_boarding_screen.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
backgroundColor: Colors.grey,
),
home:
Scaffold(
backgroundColor: Colors.grey[350],
body:Column(
children: [
Expanded(
child: PageView.builder(
itemBuilder: (context,index) =>(
Onboarding_Screen(
image: "asset/odin1.png",
title: "Learn Mythology In a Fun Way",
description:
"What's your favorite story? Mythology is full of them! Discover one of the most interesting subjects ever, including gods and goddesses, monsters and heroes. Knowledge is power, so never stop learning. From the classics to the newest stories, it's all free in My Mythology!",
)
)
),
),
Row(
children: [
SizedBox( height: 60,
width: 60,
child: ElevatedButton(onPressed: () {},
style: ElevatedButton.styleFrom(shape: CircleBorder(),),
child: SvgPicture.asset("asset/forwardarrow.svg",fit: BoxFit.contain,),)),
],
),
],
),
)
);
}
}
Also in onboarding_screen.dart:
import 'package:flutter/material.dart';
import 'onboarding.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: PageView.builder(
itemBuilder: (context, index) => (const Onboarding_Screen(
image: "asset/odin1.png",
title: "Learn Mythology In a Fun Way",
description:
"What's your favorite story? Mythology is full of them! Discover one of the most interesting subjects ever, including gods and goddesses, monsters and heroes. Knowledge is power, so never stop learning. From the classics to the newest stories, it's all free in My Mythology!",
)),
)),
Container(
color: Colors.grey[350],
child: Row(
children: [
SizedBox(
height: 60,
width: 60,
child: ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
),
child: null,
),
),
],
),
),
],
);
}
}```
i can change my background color and app bar in home just fine, but when i click the search icon which uses search delegate it all back to white, how do i change the color? just to make it clear, so before the user clicked the search icon the background and app bar was black but when they clicked it it turned to white, how do i change it?
here is the search code :
import 'package:flutter/material.dart';
import 'package:movie_app_3/model/movie_response.dart';
import 'package:movie_app_3/screens/movie_detail_screen/movie_detail_screen.dart';
import '../model/movie.dart';
import '../repository/repository.dart';
class DataSearch extends SearchDelegate {
// void initState() {
// searchBloc..getSearch(query);
// }
final movieRepo = MovieRepository();
#override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () => query = '',
)
];
}
#override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
onPressed: () => close(context, null),
);
}
#override
Widget buildResults(BuildContext context) {
return Container();
}
#override
Widget buildSuggestions(BuildContext context) {
if (query.isEmpty) return Container();
return FutureBuilder<MovieResponse>(
future: movieRepo.getSearch(query),
builder: (BuildContext context, AsyncSnapshot<MovieResponse> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.error != null && snapshot.data.error.length > 0) {
return _buildErrorWidget(snapshot.data.error);
}
return _buildHomeWidget(snapshot.data);
} else if (snapshot.hasError) {
return _buildErrorWidget(snapshot.error);
} else {
return _buildLoadingWidget();
}
},
);
}
Widget _buildHomeWidget(MovieResponse data) {
List<Movie> movies = data.movies;
return ListView.builder(
itemCount: movies.length,
itemBuilder: (context, index) {
return ListTile(
leading: FadeInImage(
image: movies[index].poster == null
? AssetImage('assets/images/no-image.jpg')
: NetworkImage("https://image.tmdb.org/t/p/w200/" +
movies[index].poster),
placeholder: AssetImage('assets/images/no-image.jpg'),
width: 50.0,
fit: BoxFit.contain),
title: Text(
movies[index].title,
style: TextStyle(fontFamily: 'Poppins'),
),
subtitle: Text(
movies[index].overview,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontFamily: 'Raleway'),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MovieDetailScreen(movie: movies[index]),
),
);
},
);
},
);
}
Widget _buildLoadingWidget() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 25.0,
width: 25.0,
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation<Color>(Colors.black),
strokeWidth: 4.0,
),
)
],
));
}
Widget _buildErrorWidget(String error) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Error occured: $error"),
],
));
}
// #override
// Widget buildSuggestions(BuildContext context) {
// final suggestedList = (query.isEmpty) ?
// recentMovies :
// movies.where((movie) => movie.toLowerCase().contains(query.toLowerCase())).toList();
// return ListView.builder(
// itemCount: suggestedList.length,
// itemBuilder: (context, i) {
// return ListTile(
// leading: Icon(Icons.movie),
// title: Text(suggestedList[i]),
// onTap: () {},
// );
// },
// );
// }
}
here is the home code :
import 'package:flutter/material.dart';
import 'package:movie_app_3/widget/drawer.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen1.dart';
import 'package:movie_app_3/screens/home_screen/widget/home_screen2.dart';
import 'package:movie_app_3/widget/search.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: 2);
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black,
Color(0xff112339),
Colors.black,
],
),
),
child: DefaultTabController(
length: 2,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
title: Text(
'Moviez',
style: TextStyle(
fontSize: 24,
color: Colors.white,
fontFamily: 'Poppins',
),
),
backgroundColor: Colors.transparent,
centerTitle: true,
actions: [
Padding(
padding: EdgeInsets.only(right: 20),
child: IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch());
},
),
),
],
bottom: TabBar(
controller: _tabController,
indicatorColor: Colors.white,
indicatorSize: TabBarIndicatorSize.tab,
indicatorWeight: 2.0,
tabs: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Discover',
style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'Genres',
style: TextStyle(fontSize: 16, fontFamily: 'Raleway'),
),
),
],
),
),
drawer: MyDrawer(),
body: TabBarView(
controller: _tabController,
children: <Widget>[
FirstTab(),
SecondTab(),
],
),
),
),
);
}
}
For customizing the Search Delegate, you have to override a method called appBarTheme and then set your custom theme on that.
** NOTE: When you override appBarTheme of SearchDelegate you have to customize evrything related to SearchBar yourself. Just like the code below. **
Do this to change the AppBar Color:
#override
ThemeData appBarTheme(BuildContext context) {
return ThemeData(
appBarTheme: const AppBarTheme(
color: MyColors.mainColor, // affects AppBar's background color
hintColor: Colors.grey, // affects the initial 'Search' text
textTheme: const TextTheme(
headline6: TextStyle( // headline 6 affects the query text
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold)),
),
);
}
And for changing the background color of suggestions:
#override
Widget buildSuggestions(BuildContext context) {
return Container(
color: Colors.black,
...
);
}
Similarly do this for results:
#override
Widget buildResults(BuildContext context) {
return Container(
color: Colors.black,
...
);
}
Hope this helps.
Add this to your "DataSearch" class
class _SearchDelegate extends SearchDelegate {
#override
ThemeData appBarTheme(BuildContext context) {
return Theme.of(context).copyWith(
scaffoldBackgroundColor: Colors.green,
);
}
If you already set your MaterialApp theme you can simply use Theme.of(context).copywith to remain body theme. Then you can override appBarTheme to change desired color/styles.
#override
ThemeData appBarTheme(BuildContext context) {
return Theme.of(context).copyWith(
//scaffoldBackgroundColor: , to change scaffold color
appBarTheme: const AppBarTheme( //to change appbar
color: Colors.black,
//titleTextStyle: , to change title text
//toolbarTextStyle: , to change toolbar text style
),
);
Kind of two questions in one here... still new to flutter and learning as I go.
My background color will not change to white. All resources on flutter.dev did not seem viable. Currently, I am using the most suggested answer which is that of backgroundColor: Colors.white. Any thoughts as to why this is not working?
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Onboarding1',
theme: ThemeData(
backgroundColor: Colors.white,
fontFamily: 'fonts/Avenir-Bold',
visualDensity: VisualDensity.adaptivePlatformDensity,
),
);
}
}```
I want to be able to style the text in the column, but TextStle is throwing an error. What is the best way to adjust the text style when in a column? Would it just be best to use a scaffold?
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Image.asset(
"assets/Onboarding1_Photo.png",
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Column(
children: <Widget>[
Text('Some Text'),
style: TextStyle(
)
],
)
],
);
}
}
Update based on the answer... What am I still doing wrong?
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Onboarding1',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
fontFamily: 'fonts/Avenir-Bold',
visualDensity: VisualDensity.adaptivePlatformDensity,
),
);
}
}
class Onboarding1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.asset(
"assets/Onboarding1_Photo.png",
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Column(
children: <Widget>[
Text('Some Text', style: TextStyle(fontSize: 24)),
],
),
],
),
);
}
}
Updated Answer with example:
class Onboarding1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Image.asset(
"assets/Onboarding1_Photo.png",
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Column(
children: <Widget>[
Text('Some Text', style: TextStyle(fontSize: 24)),
],
),
],
),
);
}
}
Original Answer :
The field you're looking for in your ThemeData is scaffoldBackgroundColor.
ThemeData(
scaffoldBackgroundColor: Colors.white,
fontFamily: 'fonts/Avenir-Bold',
visualDensity: VisualDensity.adaptivePlatformDensity),
Then wrap your column in a scaffold and it'll work.
As for your text style, in your code the style is outside of the text widget and it needs to be inside and you need to define a TextStyle with the properties.
Text('Some Text',
style: TextStyle(
color: Colors.blue,
fontSize: 20),
),
Admittedly styling text in Flutter is a bit verbose for my taste. For that reason I have my own reusabe custom text widget that saves time on my most used properties of text.
class MyTextWidget extends StatelessWidget {
final String text;
final double fontSize;
final Color color;
final double spacing;
const MyTextWidget(
{Key key, this.text, this.fontSize, this.color, this.spacing})
: super(key: key);
#override
Widget build(BuildContext context) {
return Text(
text != null ? text : ' ',
// this is part of the google fonts package it won't work if you don't have it in your project but you get the idea
style: kGoogleFontOpenSansCondensed.copyWith(
fontSize: fontSize ?? 20,
color: color ?? Colors.white70,
letterSpacing: spacing ?? 1.0),
);
}
}
Then when I need a text widget it looks like this
MyTextWidget(
text: 'Some text',
fontSize: 25,
color: Colors.white54)
We have a problem about our delivery system with progress indicator. Does anyone can suggest a library of progress indicator for flutter. The progress has a shape design. The sample image below.
Progress indicator image sample
You can achieve this using a Row, Containers and CustomClipper class. I've created a library for this purpose. You can use the library from here: progress_stepper.
The following code creates a stepper:
ProgressStepper(
width: 300,
height: 15,
stepCount: 5,
builder: (index) {
double widthOfStep = 300 / 5;
if (index == 1) {
return ProgressStepWithArrow(
width: widthOfStep,
defaultColor: Color(0xFFCECECF),
progressColor: Color(0xFFFBB040),
wasCompleted: true,
);
}
return ProgressStepWithChevron(
width: widthOfStep,
defaultColor: Color(0xFFCECECF),
progressColor: Color(0xFFFBB040),
wasCompleted: false,
);
},
)
It will create a Stepper like the following image:
You can copy paste run full code below
You can use package https://pub.dev/packages/clippy_flutter and https://pub.dev/packages/step_progress_indicator
When step index == 0 return Point else return Chevron
code snippet
StepProgressIndicator(
totalSteps: 3,
currentStep: 2,
size: 20,
selectedColor: Colors.orangeAccent,
unselectedColor: Colors.grey,
customStep: (index, color, _) => index == 0
? Point(
triangleHeight: 20.0,
edge: Edge.RIGHT,
child: Container(
color: color,
child: Center(child: Text('')),
))
: Chevron(
triangleHeight: 20.0,
edge: Edge.RIGHT,
child: Container(
color: color,
child: Center(child: Text('')),
)),
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:clippy_flutter/clippy_flutter.dart';
import 'package:step_progress_indicator/step_progress_indicator.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
StepProgressIndicator(
totalSteps: 3,
currentStep: 2,
size: 20,
selectedColor: Colors.orangeAccent,
unselectedColor: Colors.grey,
customStep: (index, color, _) => index == 0
? Point(
triangleHeight: 20.0,
edge: Edge.RIGHT,
child: Container(
color: color,
child: Center(child: Text('')),
))
: Chevron(
triangleHeight: 20.0,
edge: Edge.RIGHT,
child: Container(
color: color,
child: Center(child: Text('')),
)),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
I am trying to apply a DefaultTextStyle, but even though the style is defined and available (as established by calling DefaultTextStyle.of(context).style), it does not get applied by default to child Text objects. So what am I doing wrong, or failing to understand?
Here is the build method from my calling class, where I define my DefaultTextStyle:
Widget build(BuildContext context) {
return new MaterialApp(
onGenerateTitle: (BuildContext context) =>
Strings.of(context).getStr('app_title'),
localizationsDelegates: [
const StringsDelegate(),
GlobalWidgetsLocalizations.delegate,
],
localeResolutionCallback: Strings.resolveLocale,
// Watch out: MaterialApp creates a Localizations widget
// with the specified delegates. DemoLocalizations.of()
// will only find the app's Localizations widget if its
// context is a child of the app.
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new DefaultTextStyle(
style: new TextStyle(
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.wavy,
color: Colors.blue
),
child: new StatusPage())
);
}
And here is StatusPage, where I am trying to use the DefaultTextStyle:
class StatusPage extends MyStatelessWidget {
#override
Widget build(BuildContext context) {
TextStyle style = DefaultTextStyle.of(context).style;
print("STYLE: $style");
return new Scaffold(
appBar: new AppBar(
title: getText(context, 'app_title')
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('wibble', style:style),
new ActivityStatus(),
new MonitoringStatus()]
)));
}
}
With the code as shown, the Text "wibble" is correctly shown with the appropriate style. My understanding from the docs, is that this style should be applied by default, so I should not need the style argument to the Text constructor for "wibble".
However, if I remove the style argument I do not get the style from my DefaultTextStyle.
What am I missing?
Apply the DefaultTextStyle to the Scaffold like this and you will get this style in all the descendant Text widgets
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new StatusPage());
}
}
class StatusPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
TextStyle style = DefaultTextStyle.of(context).style;
return new Scaffold(
appBar: new AppBar(),
body: new DefaultTextStyle(
style: new TextStyle(
inherit: true,
fontSize: 20.0,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.wavy,
color: Colors.blue),
child: new Center(
child: new Column(
children: <Widget>[
new Text("hello"),
],
),
)));
}
}
I had same issue before, I think it comes when using custome fonts or changing language (at least that was my case)
the solution for me was to go MaterialApp widget and then override ALL textTheme attributes like this:
fontFamily: "STCBold",
textTheme: GoogleFonts.cairoTextTheme(textTheme).copyWith(
headline1: TextStyle(height: 1),
headline2: TextStyle(height: 1),
headline3: TextStyle(height: 1),
headline4: TextStyle(height: 1),
headline5: TextStyle(height: 1),
headline6: TextStyle(height: 1),
subtitle1: TextStyle(height: 1),
subtitle2: TextStyle(height: 1),
bodyText1: TextStyle(height: 1),
bodyText2: TextStyle(height: 1),
caption: TextStyle(height: 1),
button: TextStyle(height: 1),
overline: TextStyle(height: 1),
),
this will make all text themes have no extra padding thus all texts will be tight. but make sure to use style: Theme.of(context).textTheme.WHATEVERTEXT. in all your code