Hot reload vs hot restart in Android Studio with Flutter - android-studio

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',
),
),
),
),
);
}
}

Related

Flutter: Multiple material widgets

[![enter image description here][1]][1]A little bit of a beginner question, but I have been messing with it for a long time and looking around without finding an answer.
I am using Flutter framework and I am trying to run multiple Stateless widgets, a bottom navigation bar and a top appbar to hold menu and other navigation buttons.
I am struggling to get both running at once and I can not find a way to run them both.
At the moment, when I call home:MyBottomNavigationBar only this appears and not the other(Makes sense) But what command or solution would help me run multiple widgets? I have tried tons of different ways to use home, but nothing seems to work.
My code is very simple. Just creating a Navigation bar and appbar with stf inside main.dart.
If needed I can attach the code, but hopefully my question is clear enough.
Done In Xamarin, I can have both BottomNavBar and Couple of Nav buttons at the top easily.
[1]: https://i.stack.imgur.com/Q2qXg.png
BottomNavBar.dart in Widgets folder
import 'dart:io';
class MyBottomNavigationBar extends StatefulWidget
{
#override
MyBottomNavigationBarState createState() => MyBottomNavigationBarState();
}
class MyBottomNavigationBarState extends State<MyBottomNavigationBar>
{
int _currentIndex = 0;
final List <Widget> _children =
[
HomePage(),
ExplorePage(),
ProgressPage(),
ChallengesPage(),
ProfilePage(),
];
void onTappedBar(int index)
{
setState((){
_currentIndex=index;
});
}
#override
Widget build(BuildContext context)
{
return new Scaffold
(
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar
(
onTap: onTappedBar,
currentIndex: _currentIndex,
items:
[
BottomNavigationBarItem
(
backgroundColor: Colors.pinkAccent,
icon: new Icon(Icons.home,
color: Colors.black),
label: 'Feed',
//activeBackgroundColor: Colors.red, // this is the change
),
main.dart
void main() async
{
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
/// This is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context)
{
MyBottomNavigationBar();
}
return MaterialApp(
title: _title,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home:HomePage()
);
}
}
And then I have a widget for a couple of buttons at the top appbar, but I can only run either BottomNavBar or The AppBar buttons. I would like to have them both working at the same time.
please put the code here, it would be helpful. I personally didn't understand what you're trying to achieve. every stateless/stateful has one build method which returns a widget (that has its own build method). However, as some widgets can have more than one child (row,column,stack), you can use your pre-built layout composition and then mount it to the widget tree.
Or, simply use your custom layout by extending CustomMultiChildLayout, you can also use "Overlay"-ing, to paint directly on the canvas based on an event or a state.
||||||||||||
new answer:
I tried to reproduced the image, basically you need to use scaffold's appBar and bottomNavigationBar properties. appbar is extending PreferredSizedWidget so you can easily create your own.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
MyBottomNavigationBar();
return MaterialApp(
title: _title,
home: HomePage(),
);
}
}
home_page.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter version"),
actions: [
IconButton(icon: Icon(Icons.menu), onPressed: () {}),
IconButton(icon: Icon(Icons.account_circle), onPressed: () {}),
],
),
bottomNavigationBar: BottomNavigationBar(
backgroundColor: Colors.blue,
items: [
BottomNavigationBarItem(
backgroundColor: Colors.pinkAccent,
icon: new Icon(Icons.home, color: Colors.black),
label: 'Feed',
//activeBackgroundColor: Colors.red, // this is the change
),
BottomNavigationBarItem(
backgroundColor: Colors.pinkAccent,
icon: new Icon(Icons.home, color: Colors.black),
label: 'Feed',
//activeBackgroundColor: Colors.red, // this is the change
),
],
),
body: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height/7,
color: Colors.blue,
child: Center(child: Text("Challenges Page",style: TextStyle(fontSize: 41,color: Colors.white),),),
),
],
),
);
}
}
assuming you want to create your layout from scratch and don't want to use the scaffold's properties. the code blow is the same layout with stack, I didn't make it beautiful though, it just shows the layout without refactoring any widget.
code for home_page.dart (main.dart is the same as above)
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Stack(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height/12,
decoration: BoxDecoration(
color: Colors.blue,
boxShadow: [
BoxShadow(color: Colors.black54,blurRadius: 2,spreadRadius: .1,offset: Offset(0, 2)),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.all(18.0),
child: Text("just stack",style: TextStyle(fontSize: 21,color: Colors.white),),
),
],
),
Row(
children: [
IconButton(icon: Icon(Icons.account_circle,size: 32,), onPressed: (){}),IconButton(icon: Icon(Icons.settings,size: 32,), onPressed: (){}),
],
),
],
),
),
Positioned(
top: MediaQuery.of(context).size.height/12+1,
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height/10,
color: Colors.blue,
child: Center(child: Text("Challenges Page",style: TextStyle(fontSize: 31,color: Colors.white),)),
),
),
Positioned(
bottom:0,
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height/12,
color: Colors.blue,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
children: [
IconButton(icon: Icon(Icons.home,size: 32,), onPressed: (){}),
Text("home"),
],
),
IconButton(icon: Icon(Icons.account_circle,size: 32,), onPressed: (){}),
IconButton(icon: Icon(Icons.settings,size: 32,), onPressed: (){}),
],
),
),
),
],
),
),
),
);
}
}

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.

Flutter Web : Need menu with sub menu

How to build Menu with Submenu like shown below in image using Flutter web
As of now flutter doesn't have a NestedMenu widget. However existing widgets can help build a custom menu which can have different submenu. Here in this dartPad I have created subMenu's using two different idea.
Using the Existing PopupMenuButon Widget nested one inside another and using the offset attribute to position the subMenu.
Using the global showMenufunction which can position the menu anywhere in the screen.
You can check the two implementations shown below. Note both methods has its own caveats. Like dismissing the popups and handling selection and cancelling. However this is only to show its possible in flutter and handling those cases is out of scope for this answer.
Nested PopupMenuButton
enum WhyFarther { harder, smarter, selfStarter, tradingCharter }
class MainMenu extends StatefulWidget {
MainMenu({Key key, this.title}) : super(key: key);
final String title;
#override
_MainMenuState createState() => _MainMenuState();
}
class _MainMenuState extends State<MainMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: PopupMenuButton<WhyFarther>(
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: 2.0,
child: Container(
padding: EdgeInsets.all(8),
child: Text(widget.title),
),
),
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
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: SubMenu('Sub Menu is too long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
),
);
}
}
class SubMenu extends StatefulWidget {
final String title;
const SubMenu(this.title);
#override
_SubMenuState createState() => _SubMenuState();
}
class _SubMenuState extends State<SubMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// print(rendBox.size.bottomRight);
return PopupMenuButton<WhyFarther>(
child: Row(
children: <Widget>[
Text(widget.title),
Spacer(),
Icon(Icons.arrow_right, size: 30.0),
],
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (WhyFarther result) {
setState(() {
_selection = result;
});
},
// how much the submenu should offset from parent. This seems to have an upper limit.
offset: Offset(300, 0),
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 lot smarter'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
],
);
}
}
Using showMenu approach
class CustomMenu extends StatefulWidget {
const CustomMenu({Key key, this.title, this.rootMenu=false}) : super(key: key);
final String title;
final bool rootMenu;
#override
_CustomMenuState createState() => _CustomMenuState();
}
class _CustomMenuState extends State<CustomMenu> {
WhyFarther _selection = WhyFarther.smarter;
#override
Widget build(BuildContext context) {
// This menu button widget updates a _selection field (of type WhyFarther,
// not shown here).
return Padding(
padding: const EdgeInsets.all(2.0),
child: GestureDetector(
onTap: () {
// This offset should depend on the largest text and this is tricky when
// the menu items are changed
Offset offset = widget.rootMenu?Offset.zero:Offset(-300,0);
final RenderBox button = context.findRenderObject();
final RenderBox overlay =
Overlay.of(context).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
button.localToGlobal(Offset.zero, ancestor: overlay),
button.localToGlobal(button.size.bottomRight(Offset.zero),
ancestor: overlay),
),
offset & overlay.size,
);
showMenu(
context: context,
position: position,
items: <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: CustomMenu(title: 'Sub Menu long'),
),
const PopupMenuItem<WhyFarther>(
value: WhyFarther.tradingCharter,
child: Text('Placed in charge of trading charter'),
),
]).then((selectedValue){
// do something with the value
if(Navigator.canPop(context)) Navigator.pop(context);
});
},
child: Material(
textStyle: Theme.of(context).textTheme.subtitle1,
elevation: widget.rootMenu?2.0:0.0,
child: Padding(
padding: widget.rootMenu? EdgeInsets.all(8.0):EdgeInsets.all(0.0),
child: Row(
children: <Widget>[
Text(widget.title),
if(!widget.rootMenu)
Spacer(),
if(!widget.rootMenu)
Icon(Icons.arrow_right),
],
),
),)
),
);
}
}
In standard Flutter library (material.dart), there is an abstract class PopupMenuEntry from which all children of PopupMenuButton are inherited. Currently, there are three concrete subclasses: PopupMenuItem (regular item you see all the time), 'CheckedPopupMenuItem' (regular item + checkbox) and PopupMenuDivider (horizontal line). There is nothing preventing us from implementing our own subclass.
Using the first answer of #AbhilashChandran and modifying it a bit, we can create the following generic class:
import 'package:flutter/material.dart';
/// An item with sub menu for using in popup menus
///
/// [title] is the text which will be displayed in the pop up
/// [items] is the list of items to populate the sub menu
/// [onSelected] is the callback to be fired if specific item is pressed
///
/// Selecting items from the submenu will automatically close the parent menu
/// Closing the sub menu by clicking outside of it, will automatically close the parent menu
class PopupSubMenuItem<T> extends PopupMenuEntry<T> {
const PopupSubMenuItem({
#required this.title,
#required this.items,
this.onSelected,
});
final String title;
final List<T> items;
final Function(T) onSelected;
#override
double get height => kMinInteractiveDimension; //Does not actually affect anything
#override
bool represents(T value) => false; //Our submenu does not represent any specific value for the parent menu
#override
State createState() => _PopupSubMenuState<T>();
}
/// The [State] for [PopupSubMenuItem] subclasses.
class _PopupSubMenuState<T> extends State<PopupSubMenuItem<T>> {
#override
Widget build(BuildContext context) {
return PopupMenuButton<T>(
tooltip: widget.title,
child: Padding(
padding: const EdgeInsets.only(left: 16.0, right: 8.0, top: 12.0, bottom: 12.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: Text(widget.title),
),
Icon(
Icons.arrow_right,
size: 24.0,
color: Theme.of(context).iconTheme.color,
),
],
),
),
onCanceled: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
onSelected: (T value) {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
widget.onSelected?.call(value);
},
offset: Offset.zero, //TODO This is the most complex part - to calculate the correct position of the submenu being populated. For my purposes is does not matter where exactly to display it (Offset.zero will open submenu at the poistion where you tapped the item in the parent menu). Others might think of some value more appropriate to their needs.
itemBuilder: (BuildContext context) {
return widget.items
.map(
(item) => PopupMenuItem<T>(
value: item,
child: Text(item.toString()), //MEthod toString() of class T should be overridden to repesent something meaningful
),
)
.toList();
},
);
}
}
Usage of this class is simple and intuitive:
PopupMenuButton<int>(
icon: Icon(Icons.arrow_downward),
tooltip: 'Parent menu',
onSelected: (value) {
//Do something with selected parent value
},
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
value: 10,
child: Text('Item 10'),
),
PopupMenuItem<int>(
value: 20,
child: Text('Item 20'),
),
PopupMenuItem<int>(
value: 50,
child: Text('Item 50'),
),
PopupSubMenuItem<int>(
title: 'Other items',
items: [
100,
200,
300,
400,
500,
],
onSelected: (value) {
//Do something with selected child value
},
),
];
},
)
The result is something like this:
There are a couple of drawbacks for this approach:
Obviously, the submenu is displayed not at the location you wanted it to be displayed - may be dealt with by some complex calculations;
Even though several submenus can be placed one inside another, I am not sure that the top ones will be closed correctly when bottom ones are closed (or the value is selected) - may be dealt with by Navigator calls and checks;
Both parent menu and submenues should have values of the same type - mayn be dealt with by using subclasses;
The need to specify onSelected method twice (for parent menu and for child menu) - may be dealt with by using methods or closures;
Some other things I may have not thought of - may be dealt with by writing comments below.
The PopupSubMenuItem class can be expanded to include something like final String Function(T) formatter; to represent your values in a meaningful way, but for the sake of brevity this functionality was omitted.

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.

Resources