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)
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,
),
),
],
),
),
],
);
}
}```
There's a syntax error at "Center(". what could be wrong?
Here's the message i'm receiving: "Creates a widget that centers its child."
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
Center(
child: Text(
'n',
style: TextStyle(
color: Colors.black,
fontSize: 90,
fontFamily: 'Aclonica',
),
),
),
);
}
}
You should add "body:" before "Center(", because Scaffold doesn't have a positional parameters
The Scaffold takes the main widget in a parameter called body. So you should pass the Center widget in the body parameter of the Scaffold.
So something like,
Scaffold(
backgroundColor: Colors.white,
body: Center(
...
)
)
Try This:
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
child: Column(
mainAxisAlignment : MainAxisAlignment.center,
crossAxisAlignment : CrossAxisAlignment.center,
children : [
Text(
'n',
style: TextStyle(
color: Colors.black,
fontSize: 90,
fontFamily: 'Aclonica',
),])
),
);
}
}
Try This:
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment : MainAxisAlignment.center,
crossAxisAlignment : CrossAxisAlignment.center,
children : [
Text(
'n',
style: TextStyle(
color: Colors.black,
fontSize: 90,
fontFamily: 'Aclonica',
),])
),
);
}
}
When using a widget, it's best to read through it's documentation once. According to the Scaffold's documentation here, the content of the Scaffold should be placed within the body property, which is a positional parameter (means you need to state the param when initializing the Scaffold):
import 'package:flutter/material.dart';
class SplashPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center( // Just need to add the `body` property here
child: Text(
'n',
style: TextStyle(
color: Colors.black,
fontSize: 90,
fontFamily: 'Aclonica',
),
),
),
);
}
}
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
I want to find a solution to mimic attached image Android contraint layout on a Flutter wrapped widgets structure.
In this case, blue text TextView width is wrap content and image (dollar sign) must take same width.
Any suggestions? Thanks a lot!
This is my current code, a simple column, I tried a lot of alternatives but I can't figure it out logically :/
Widget _getPublisherLogoImage() {
return ClipOval(
child: CachedNetworkImage(
imageUrl: _publisherLogo,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
width: 50,
height: 50,
),
);
}
Widget _getNewsItemHour(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 8),
child: Text(DateUtils.getHoursMinutesStringDate(_timestamp),//'09:35',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold))
);
}
Widget _getNewsItemQuotation() {
return Padding(
padding: EdgeInsets.only(top: 8),
child: Text('\$$_price',
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.bold))
);
}
.
.
.
Column(
children: <Widget>[
_getPublisherLogoImage(),
_getNewsItemHour(context),
_getNewsItemQuotation()
],
)
.
.
.
To match the text to the image, I use a technique where an IntrinsicWidth widget wraps a Column, whose crossAxisAlignment is stretched.
Change the image width in the code from width: 200 to whatever you want, and the text underneath will match its size.
P.S. The second text widget at the bottom of the screen scales to the screen size.
Code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Replicate Android Layout',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Replicate Android Layout')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
_getPublisherLogoImage(),
FittedBox(
fit: BoxFit.fitWidth, child: _getNewsItemHour(context)),
],
),
),
_getNewsItemQuotation(context),
],
),
),
);
}
}
Widget _getPublisherLogoImage() {
return Image(
image: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
width: 200,
);
}
Widget _getNewsItemHour(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 10),
child: Text('09.35',
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.normal)));
}
Widget _getNewsItemQuotation(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double _price = 60.59;
return Text(
'\$$_price',
style: TextStyle(
fontSize: width * 0.25,
color: Colors.grey,
),
);
}
Run in dartpad.
I am trying to create aPopupMenuButton.I have used the PopupMenuButton class.
PopupMenuButton(
padding: EdgeInsets.only(right: 8.0),
offset: Offset(-16, 0),
child: Container(
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.all(
Radius.circular(16.0),
)),
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
child: Text(
"Category",
style: TextStyle(color: Colors.white),
),
),
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
//I want this context to be scrollable with some fixed height on the screen
child: Row(
children: <Widget>[
Icon(Icons.arrow_right),
Text("Dairy & Bakery")
],
),
value: '1'),
],
)
I have tried implementing the PreferredSizeWidget but is not working on PopupMenuButton.
Edit: i meant fixed height :S
PopUpMenuButton does not support a fixed height. But what u can do is adjust the PopUpMenu Package.
Something similar is done
here
with the DropdownButton. For the PopUpMenu the implemenatition should work analogously, as both have the same strucktur. (Route, RouteLayout and PopUpMenu)
Edit:
You take a look at the the original code of the DropdownButton and then look at the changes the person did to it in the custom edition.
Then you take the code of the PopUpMenuButton and copy them into your own project and adjust them like it was done with the DropDownButton.
Then you use ure custom version of the PopUpMenuButton with the argument height.
Edit 2:
As you had some problems doing what I meant, I did it for you:
Just copy this file into your directory and import it into your code.
Then use CustomPopupMenuButton with a height instead of the original one.
Usage:
import 'package:flutter/material.dart';
import 'custom_popup_menu_button.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
enum WhyFarther { harder, smarter, selfStarter, tradingCharter }
class _HomeState extends State<Home> {
WhyFarther _selection;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'it does work here',
style: TextStyle(fontSize: 20),
),
),
body: Center(
child: CustomPopupMenuButton<WhyFarther>(
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
height: 100,
itemBuilder: (BuildContext context) => <PopupMenuEntry<WhyFarther>>[
const PopupMenuItem<WhyFarther>(
value: WhyFarther.harder,
child: Text('Working a lot harder'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.smarter,
child: Text('Being a lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.selfStarter,
child: Text('Being a self-starter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
)),
);
}
}
If anything is not working feel free to ask, perhaps I will look into it later.