Repeat background pattern image in flutter - flutter-layout

I'm new to Flutter and currently try to make a website. I have a pattern image like this:
Now I wanna set it to be background of my website with this code:
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Container(
height: size.height,
width: size.width,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage("assets/images/double-bubble-dark.png"))),
);
}
}
But here the result:
How can I make it fit with & responsive with the browser window instead of scale the image?

Just use
Image.asset(
"assets/images/double-bubble-dark.png",
repeat: ImageRepeat.repeat,
)

Related

How to I update the layout of my home screen when something in the navigation drawer is pressed in Flutter?

I want to make a Navigation drawer application. But instead of a pushing a new screen when something is presses I want update my initial screen. I cannot use setState(){} in my drawer to update the state of my home screen.
Please help me with this.
You can pass a function from your HomeScreen to your Drawer.
In your Drawer:
Class CustomDrawer{
final function updateMainScreen;
CustomDrawer(this.updateMainScreen);
}
In your MainScreen:
child: CustomDrawer(updateScreenFunction), //this function is where your MainScreen state gets changed
This way you can change whatever you want in your HomeScreen from anywhere else.
UPDATE: More Complete example. Note that this is very rough and only so you get an idea of how this works.
HomeScreenState:
class _HomeScreenWidgetState extends State<HomeScreenWidget> {
var containerColor = Colors.red;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: (Text('Hello')),
),
body: Container(
child: Column(
children: <Widget>[
Container(
height: 500,
width: 300,
color: containerColor,
),
CustomDrawer(
changeHomeScreen: changeContainerColor,
)
],
),
));
}
void changeContainerColor(Color col) {
setState(() {
containerColor = col;
});
}
}
The Mock Drawer widget:
class CustomDrawer extends StatelessWidget {
final Function changeHomeScreen;
CustomDrawer({this.changeHomeScreen});
#override
Widget build(BuildContext context) {
return Container(
child: FlatButton(
child: Text("Action in Drawer"),
onPressed: () => changeHomeScreen(Colors.blue),
),
);
}
}
You could also use a Provider for state management. Use the drawer to update the state (model) and use notifylisteners() to update your view. With conditionals pulled from the model, it is realy simple to create a 'single page' app.

Hot reload vs hot restart in Android Studio with Flutter

I'm testing my Flutter starter app on virtual as well as physical device. The problem is that the app doesn't update on the screen while hot-reloading (this is configured to work at every file-save), but only on hot-restart. On the screenshot this corresponds to the right button, not the left.
Is it normal or is something wrong?
Just in case, this is the contents of my main.dart file:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Center(
child: Text('Hi Everybody!'),
),
backgroundColor: Colors.blueGrey[900],
),
body: Center(
child: Image(
image: AssetImage(
'images/diamond.png',
),
),
),
),
),
);
}
You are writing everything inside main function. so hot reload is not working.
They mentioned this in Flutter Documentaion
As a general rule, if the modified code is downstream of the root
widget’s build method, then hot reload behaves as expected. However,
if the modified code won’t be re-executed as a result of rebuilding
the widget tree, then you won’t see its effects after hot reload.
so you need to write your code below root widget.
Write code like this:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Center(
child: Text('Hi Everybody!'),
),
backgroundColor: Colors.blueGrey[900],
),
body: Center(
child: Image(
image: AssetImage(
'images/diamond.png',
),
),
),
),
);
}
}

How to add Pie chart in hole of Donut chart in Flutter, I tried with Stack widget but it's working for text only

I am trying to fill the hole of donut chart with pie chart in Flutter for my project but unable to do so.
Expanded(
child:Stack(
children:<Widget>[
charts.PieChart(
_seriesPieData1,
animate: true,
animationDuration: Duration(milliseconds: 500),
selectionModels: [
new charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
),
],
defaultRenderer: new charts.ArcRendererConfig(arcWidth: 25),
),
Center
(
child: charts.PieChart(
_seriesPieData,
animate: true,
animationDuration: Duration(milliseconds: 500),
selectionModels: [
new charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
),
],
defaultRenderer: new charts.ArcRendererConfig(arcRendererDecorators: [
new charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.inside)
],),
),
),
],
),
),
I use Container and set same height and width of these two chart.
child: Stack(
children: <Widget>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
full code
import 'package:flutter/material.dart';
/// Donut chart example. This is a simple pie chart with a hole in the middle.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:pie_chart/pie_chart.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(
// 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.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
Map<String, double> dataMap = new Map();
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
super.initState();
dataMap.putIfAbsent("Flutter", () => 5);
dataMap.putIfAbsent("React", () => 3);
dataMap.putIfAbsent("Xamarin", () => 2);
dataMap.putIfAbsent("Ionic", () => 2);
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
var dpc = DonutPieChart.withSampleData();
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Stack(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
,
/* Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),*/
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class DonutPieChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
DonutPieChart(this.seriesList, {this.animate});
/// Creates a [PieChart] with sample data and no transition.
factory DonutPieChart.withSampleData() {
return new DonutPieChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.PieChart(seriesList,
animate: animate,
// Configure the width of the pie slices to 60px. The remaining space in
// the chart will be left as a hole in the center.
defaultRenderer: new charts.ArcRendererConfig(arcWidth: 60));
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
new LinearSales(0, 100),
new LinearSales(1, 75),
new LinearSales(2, 25),
new LinearSales(3, 5),
];
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}

Flutter | How to show AlertDialog on top of any overlay?

How to show AlertDialog always on top of anything on the screen?
Code:
import 'package:flutter/material.dart';
class CountriesField extends StatefulWidget {
#override
_CountriesFieldState createState() => _CountriesFieldState();
}
class _CountriesFieldState extends State<CountriesField> {
final FocusNode _focusNode = FocusNode();
OverlayEntry _overlayEntry;
final LayerLink _layerLink = LayerLink();
#override
void initState() {
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
} else {
// this._overlayEntry.remove();
}
});
}
OverlayEntry _createOverlayEntry() {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
return OverlayEntry(
builder: (context) => Positioned(
width: size.width,
child: CompositedTransformFollower(
link: this._layerLink,
showWhenUnlinked: false,
offset: Offset(0.0, size.height + 5.0),
child: Material(
elevation: 4.0,
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
children: <Widget>[
ListTile(
title: Text('Syria'),
onTap: () {
print('Syria Tapped');
},
),
ListTile(
title: Text('Lebanon'),
onTap: () {
print('Lebanon Tapped');
},
)
],
),
),
),
));
}
#override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: this._layerLink,
child: Material(
child: TextFormField(
focusNode: this._focusNode,
decoration: InputDecoration(labelText: 'Country'),
),
),
);
}
}
class FormPage extends StatefulWidget {
#override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Material(elevation: 4.0, child: CountriesField()),
RaisedButton(
child: Text('Help dialog'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Help"),
content: Text("This should show on top of any overlay"),
actions: <Widget>[
FlatButton(
child: Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
},
)
],
),
);
}
}
There is no easy way to make dialogs appear on top of overlays. Depends on your use case, you can either convert both to Overlay, or convert both to Dialog.
This is an example of converting both to dialogs, using showDialog method:
You don't have to return an AlertDialog widget when showing a dialog, for example, here I'm returning a Container with white filling, and contains a ListView for the "Menu A" dialog in the back.
When using showDialog, you get automatic features such as dimming the background and click anywhere outside to dismiss. If you don't want these or any other dialog things, and if you cannot find a way to disable them easily, you can always go the other way around and convert both to Overlay instead.
For overlays, whichever gets inserted latest, is displayed on top.
This isn't really a "fix", but a potential workaround for this is to basically not use Overlays and rely on a top level Stack.
If you are using Positioned in your Overlay anyway, putting your widget in a top level Stack doesn't interfere with things like Dialogs (and you potentially have more control over which areas of your app show the overlay).
Example:
class StackOverlayState extends State<StackOverlay> {
bool _showOverlay = true; // This could also easily be a list of widgets
Widget build(BuildContext context) {
return Stack(
children: [
Positioned.fill(
child: Scaffold(
body: /// etc..
),
),
if (_showOverlay)
MyOverlayWidget(),
],
);
}
}
I was using Overlays, and switching to just using a Stack instead seems to have caused no issues and required no code changes in the Overlay widget itself, but YMMV.

Flutter, custom scroll effects

I would like to implement a layout like in this video (at 5:50) https://www.youtube.com/watch?v=KYUTQQ1usZE&index=1&list=PL23Revp-82LKxKN9SXqQ5Nxaa1ZpYEQuaadd#t=05m50s
How would you tackle this? I tried with a ListView & GridLayout, but this seems to be limited to archive this. Would I need to use something like CustomMultiChildLayout (https://docs.flutter.io/flutter/widgets/CustomMultiChildLayout-class.html) or maybe a CustomScrollView (https://docs.flutter.io/flutter/widgets/CustomScrollView-class.html)?
Any suggestions would be appreciated, thx :)
Update:
As far as I could find out, I would need to use a CustomScrollView (Correct me if I am wrong). But I am a bit overwhelmed with the options that the Flutter framework leaves me. And I am not sure from the documentation what classes I need to extend or which interfaces I would need to implement to archive my goal. I dont't know how deep I need to dive into the framework. There are the following classes involved when it comes to slivers and lists with custom scroll effects:
RenderSliver This is really the base for render objects which implement scroll effects. I guess it would be overkill to reimplement this. But maybe subclass it and start from there (maybe overkill too)?
RenderSliverMultiBoxAdaptor If we go higher in the hierarchy we find the abstract class RenderSliverMultiBoxAdaptor. A sliver with multiple box children. A RenderSliverBoxChildManager This provides children on the fly for the RenderSliverMultiBoxAdaptor. These are both abstract classes. So maybe start here and extend these classes?
RenderSliverList This extends the RenderSliverMultiBoxAdaptor and provides box children laid out along the main axis. The children are delivered by a class which implement RenderSliverBoxChildManager.
SliverMultiBoxAdaptorElement implements RenderSliverBoxChildManager. So RenderSliverList and SliverMultiBoxAdaptorElement are a concrete implementation of RenderSliverMultiBoxAdaptor and RenderSliverBoxChildManager. I thought that I could extend these classes. But if I do so, I would anyway have to reimplement the performLayout method. So maybe reuse the SliverMultiBoxAdaptorElement and extend RenderSliverMultiBoxAdaptor?
SliverList This class eventually creates the render object (a RenderSliverList with a SliverMultiBoxAdaptorElement as a child manager) and provides a SliverChildDelegate to the SliverMultiBoxAdaptorElement, which in turn lazily builds children for SliverMultiBoxAdaptorWidget. The SliverList places multiple box children in a linear array along the main axis. It uses a class that extends SliverChildDelegate to provide children on the fly. It can be placed inside a CustomScrollViews slivers array. This is the most concrete sliver which creates a list in a CustomScrollView. So could I also archive my goal to have a layout according to the video simply with this? So far I tried to provide the CustomScrollView a ScrollController to intercept the scroll offset and then build the child elements according to the scroll offset and the index of the element with a SliverChildBuilderDelegate. But when doing so, the scrollview does not scroll anymore. It only scrolls, when the total height of all cells exceeds the viewport.
So do I really have to extend RenderSliverMultiBoxAdaptor and implement the perfromLayout method myself? For me it seems to be the only option now...
It's hard to understand slivers logic of from the first look.
But what is important is SliverGeometry class
paintOrigin - think about it as kind of delta y. When you want to make widget
fixed on a screen, you need to push it from the top.
constraints.scrollOffset shows scroll offset of logical place of
widget.
scrollExtent shows logical height of widget. It help widget
to know that you scrolled all slivers.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey _key = GlobalKey();
RenderObject ansestor;
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback(_getPosition);
super.initState();
}
_getPosition(_) {
setState(() {
ansestor = _key.currentContext.findRenderObject();
});
}
#override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return CustomScrollView(
physics: ClampingScrollPhysics(),
key: _key,
slivers: <Widget>[
CustomSliver(
isInitiallyExpanded: true,
ansestor: ansestor,
child: _Item(
title: 'first title',
fileName: 'item_1',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'second title',
fileName: 'item_2',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'third title',
fileName: 'item_3',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'fourth title',
fileName: 'item_4',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'fifth title',
fileName: 'item_5',
),
),
CustomSliver(
ansestor: ansestor,
child: _Item(
title: 'first title',
fileName: 'item_6',
),
),
SliverToBoxAdapter(
child: Container(
child: Center(
child: Text('end'),
),
height: 1200,
color: Colors.green.withOpacity(0.3),
),
),
],
);
});
}
}
class CustomSliver extends SingleChildRenderObjectWidget {
CustomSliver({
this.child,
Key key,
this.ansestor,
this.isInitiallyExpanded = false,
}) : super(key: key);
final RenderObject ansestor;
final bool isInitiallyExpanded;
#override
RenderObject createRenderObject(BuildContext context) {
return CustomRenderSliver(
isInitiallyExpanded: isInitiallyExpanded,
);
}
#override
void updateRenderObject(
BuildContext context,
CustomRenderSliver renderObject,
) {
renderObject.ansestor = ansestor;
renderObject.markNeedsLayout();
}
final Widget child;
}
class CustomRenderSliver extends RenderSliverSingleBoxAdapter {
CustomRenderSliver({
RenderBox child,
this.isInitiallyExpanded,
}) : super(child: child);
final double max = 250;
final double min = 100;
RenderObject ansestor;
final bool isInitiallyExpanded;
void performLayout() {
var constraints = this.constraints;
double distanceToTop;
double maxExtent;
if (ansestor != null) {
distanceToTop = child.localToGlobal(Offset.zero, ancestor: ansestor).dy;
}
if (ansestor == null) {
if (isInitiallyExpanded) {
maxExtent = max;
} else {
maxExtent = min;
}
} else {
if (constraints.scrollOffset > 0) {
maxExtent = (max - constraints.scrollOffset).clamp(0.0, max);
} else if (distanceToTop < max) {
maxExtent = min + (3 * (250 - distanceToTop) / 5);
} else {
maxExtent = min;
}
}
child.layout(
constraints.asBoxConstraints(maxExtent: maxExtent),
parentUsesSize: true,
);
var paintExtent = math.min(maxExtent, constraints.remainingPaintExtent);
geometry = SliverGeometry(
paintOrigin: maxExtent == 0 ? 0.0 : constraints.scrollOffset,
scrollExtent: max,
paintExtent: paintExtent,
maxPaintExtent: paintExtent,
hasVisualOverflow: true,
);
constraints = constraints.copyWith(remainingPaintExtent: double.infinity);
setChildParentData(child, constraints, geometry);
}
}
class _Item extends StatelessWidget {
const _Item({
Key key,
#required this.title,
#required this.fileName,
}) : super(key: key);
final String title;
final String fileName;
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return Container(
height: 250,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/$fileName.png'),
fit: BoxFit.fitWidth,
),
),
child: Padding(
padding: const EdgeInsets.only(top: 40),
child: Text(
title,
style: Theme.of(context).textTheme.headline4.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 60,
),
),
),
);
},
);
}
}

Resources