Wrap middle element to new row if needed? - flutter

I have a navigation bar at the bottom of a multi-page form, with buttons to go back or forward, and an indicator for the current page.
Right now, I have the indicator place in a Row above another Row that contains the buttons, like this:
This works, and it will work even on small display sizes. However, I would rather have the indicators placed on the same row as the buttons if there is enough space, like this (except that the indicator is not centered):
The problem is, this could be too wide for some devices, especially if there are more than just a few pages. In that case, I would like either the page indicator or the buttons to "wrap" to a new row, as in the current design.
It would be easy to put everything in a Wrap, but that will make the NEXT-button wrap instead of the page indicator, since that is the last element.
Is there an easy way to make the middle element wrap onto a new row if needed? Or does one have to resort to the black magic of manually calculating sizes and creating two different layouts?

The easiest solution is to add invisible wrap to calculate the height.
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: SafeArea(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int currentPageIndex = 1;
int pageCount = 8;
#override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
currentPageIndex.toString(),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
RaisedButton(
child: Text('+1 page'),
onPressed: () => setState(() => ++pageCount),
),
SizedBox(
width: 10,
),
RaisedButton(
child: Text('-1 page'),
onPressed: () => setState(() => --pageCount),
),
],
)
],
),
),
),
Container(
child: _BottomNavigation(
onPrev: () => setState(() => --currentPageIndex),
onNext: () => setState(() => ++currentPageIndex),
currentCount: currentPageIndex,
totalCount: pageCount,
),
),
],
);
}
}
class _BottomNavigation extends StatelessWidget {
const _BottomNavigation({
Key key,
#required this.totalCount,
#required this.currentCount,
#required this.onNext,
#required this.onPrev,
}) : assert(totalCount != null),
assert(currentCount != null),
assert(onNext != null),
assert(onPrev != null),
super(key: key);
final void Function() onPrev;
final void Function() onNext;
final int totalCount;
final int currentCount;
#override
Widget build(BuildContext context) {
return Stack(
children: [
buildHelper(),
buildIndicatorBar(),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_button(
'<< PREIOUS',
onPrev,
isVisible: currentCount > 1,
),
_button(
'NEXT >>',
onNext,
isVisible: currentCount < totalCount,
),
],
),
),
],
);
}
Wrap buildHelper() {
return Wrap(
children: List.generate(
totalCount,
(index) {
return Container(
width: index == 0 ? 250 : 15,
height: 20,
);
},
),
);
}
Row buildIndicatorBar() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(totalCount, (index) {
var isLast = totalCount != index + 1;
var isCurrent = currentCount == index + 1;
return Container(
height: isCurrent ? 20 : 10,
width: isCurrent ? 20 : 10,
margin: EdgeInsets.only(right: isLast ? 10 : 0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isCurrent ? Colors.blueAccent : null,
border: Border.all(
color: Colors.blueAccent,
),
),
);
}),
);
}
Widget _button(String text, void Function() onPress, {bool isVisible}) {
return Visibility(
visible: isVisible,
child: GestureDetector(
onTap: onPress,
child: Text(text),
),
);
}
}

Related

Is there a Flutter equivalent to Bootstrap Scrollspy?

I am looking for a flutter package that is equivalent to that of Bootstrap’s Scrollspy:
https://getbootstrap.com/docs/4.0/components/scrollspy/
The intended functionality is to have a vertical scrollable list of items with a sticky horizontal scrollable “header/navbar menu” on top of it. When the user scrolls through the vertical list and reaches a new “section” this is reflected in the horizontal navbar by highlighting the “section name” in the navbar and scrolling to it if necessary. When the user presses on a section name in the horizontal navbar, it should scroll to the start of that section in the vertical list.
Ex:
Section1 !!!Section2!!! Section3 Section4
——————————————————————
(Section1 is not visible)
!!!Section2!!!
Item3
Item4
Section3
Item1
Item2
Section4
Item5
Item6
I think you can achieve this with the scrollable_positioned_list package made by Google Fuchsia Authors.
The ScrollablePositionedList provides a ItemPositionsListener:
_itemPositionsListener.itemPositions.addListener(() {
final positions = _itemPositionsListener.itemPositions.value;
setState(() {
_topItem = positions.isNotEmpty ? positions.first.index : null;
});
});
Full source code
import 'package:flutter/material.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
);
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _nbItems = 6;
final _itemHeight = 200.0;
final _itemPositionsListener = ItemPositionsListener.create();
int _topItem = 0;
#override
void initState() {
super.initState();
_itemPositionsListener.itemPositions.addListener(() {
final positions = _itemPositionsListener.itemPositions.value;
setState(() {
_topItem = positions.isNotEmpty ? positions.first.index : null;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: List.generate(
_nbItems,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: EdgeInsets.all(4.0),
decoration: _topItem == index
? BoxDecoration(
color: Colors.black26,
border: Border.all(color: Colors.black54),
)
: BoxDecoration(),
child: Text(
'S$index',
style: TextStyle(
fontWeight: _topItem == index
? FontWeight.bold
: FontWeight.normal,
),
),
),
),
),
),
Expanded(
child: ScrollablePositionedList.builder(
itemCount: _nbItems,
itemBuilder: (context, index) => SizedBox(
height: _itemHeight,
child: Card(
child: Text('Item $index'),
),
),
itemPositionsListener: _itemPositionsListener,
),
),
],
),
);
}
}

Widget width not updating after value change

I am trying to build a side menu that will open and close when the arrow icon at the bottom of the vertical app bar seen in the screenshots below is pressed. I am currently doing this by using a global bool value named isleftWidgetCollapsed which will change the width of the side menu to 0 if isleftWidgetCollapsed is set to true.
It seems to be working correctly but only when I resize the app window as seen in the screenshots below. How can I get it to work on the press of the IconButton and without having to resize the app window every time?
Section of code from buildLeftMenu.dart:
Widget buildLeft(context, HomeViewModel model) {
final _scrollbar = ScrollController();
return Material(
textStyle: TextStyle(
color: Colors.white70,
fontFamily: 'Lato',
),
child: Row(
children: [
Container(
width: (gb.isleftWidgetCollapsed==true)
? 0
: MediaQuery.of(context).size.width * .20, //21.width,
height: 100.height,
decoration: BoxDecoration(
color: MainTheme.primary[50], //Colors.blueAccent[400],
),
Section of code from the mainHomeView.dart:
body: Container(
child: Row(
children: [
VerticalAppBar(),
buildLeft(context, HomeViewModel()),
...
onPressed section from VerticalAppBar.dart:
leading: RotatedBox(
quarterTurns: 1,
child: IconButton(
icon: Icon(gb.isleftWidgetCollapsed
? Icons.arrow_right
: Icons.arrow_left),
onPressed: () {
setState(() {
gb.isleftWidgetCollapsed = !gb.isleftWidgetCollapsed;
buildLeft(context, HomeViewModel());
});
},
)),
),
);
}
}
globals.dart :
library my_prj.globals;
bool isLoggedIn = false;
bool isleftWidgetCollapsed = false;
The call to buildLeft inside onPressed is doing nothing:
onPressed: () {
setState(() {
gb.isleftWidgetCollapsed = !gb.isleftWidgetCollapsed;
buildLeft(context, HomeViewModel());
});
},
Here is a solution using hooks_riverpod package. You will find all the info about this package here: http://riverpod.dev/
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: HomePage(),
),
),
);
}
class HomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final menuOpened = useProvider(menuOpenedProvider).state;
return Scaffold(
body: Stack(
children: [
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: 0,
right: 0,
bottom: 0,
left: menuOpened
? kVerticalBarWidth + kLeftMenuWidth
: kVerticalBarWidth,
child: Content(),
),
AnimatedPositioned(
duration: Duration(milliseconds: 300),
top: 0,
bottom: 0,
left: menuOpened
? kVerticalBarWidth
: kVerticalBarWidth - kLeftMenuWidth,
child: LeftMenu(),
),
Align(alignment: Alignment.centerLeft, child: VerticalAppBar()),
],
),
);
}
}
class VerticalAppBar extends HookWidget {
#override
Widget build(BuildContext context) {
final menuOpened = useProvider(menuOpenedProvider).state;
return Container(
width: kVerticalBarWidth,
color: kVerticalBarColor,
child: Align(
alignment: Alignment.bottomCenter,
child: IconButton(
onPressed: () =>
context.read(menuOpenedProvider).state = !menuOpened,
icon: Icon(menuOpened ? Icons.arrow_left : Icons.arrow_right)),
),
);
}
}
class LeftMenu extends HookWidget {
#override
Widget build(BuildContext context) {
return Container(
color: kLeftMenuColor,
width: 200.0,
padding: EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...List.generate(20, (index) => Text('Menu Item $index')),
],
),
);
}
}
class Content extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: kContentColor,
child: Center(
child: Text('CONTENT'),
),
);
}
}
// Provider for the Menu State
final menuOpenedProvider = StateProvider((ref) => true);
// Some constants
const double kVerticalBarWidth = 48.0;
const double kLeftMenuWidth = 200.0;
const Color kVerticalBarColor = Color(0xffc19277);
const Color kLeftMenuColor = Color(0xffe1bc91);
const Color kContentColor = Color(0xff62959c);

Listview scrolling and selecting Textfield afterwards is freezing my app

I am using the package
country_code_picker: ^1.4.0
https://pub.dev/packages/country_code_picker#-installing-tab-
with flutter 1.17.3
Which is pretty much one of the only country code picker packages. But I have one serious problem an I don't have a clue what it could be.
When I run this code
import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
App();
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: TestWidget(),
);
}
}
class TestWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(body: _buildCountryPicker(context));
}
Widget _buildCountryPicker(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Center(
child: CountryCodePicker(
initialSelection: 'NL',
),
),
);
}
}
And I open the dialog to select a country. I scroll in the list and then select the TextField my keyboard opens and when I try to type something my entire app freezes. I can't even hot reload. I don't get a single error.
I am running this on my Huawei P30, but I also experience this on other android devices. I don't know if this is a flutter bug or a country code picker bug.
I think it is probably in this widget somewhere. If anyone could point me in the right direction it would help me alot!
class SelectionDialog extends StatefulWidget {
final List<CountryCode> elements;
final bool showCountryOnly;
final InputDecoration searchDecoration;
final TextStyle searchStyle;
final TextStyle textStyle;
final WidgetBuilder emptySearchBuilder;
final bool showFlag;
final double flagWidth;
final Size size;
final bool hideSearch;
/// elements passed as favorite
final List<CountryCode> favoriteElements;
SelectionDialog(
this.elements,
this.favoriteElements, {
Key key,
this.showCountryOnly,
this.emptySearchBuilder,
InputDecoration searchDecoration = const InputDecoration(),
this.searchStyle,
this.textStyle,
this.showFlag,
this.flagWidth = 32,
this.size,
this.hideSearch = false,
}) : assert(searchDecoration != null, 'searchDecoration must not be null!'),
this.searchDecoration =
searchDecoration.copyWith(prefixIcon: Icon(Icons.search)),
super(key: key);
#override
State<StatefulWidget> createState() => _SelectionDialogState();
}
class _SelectionDialogState extends State<SelectionDialog> {
/// this is useful for filtering purpose
List<CountryCode> filteredElements;
#override
Widget build(BuildContext context) => SimpleDialog(
titlePadding: const EdgeInsets.all(0),
title: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
IconButton(
padding: const EdgeInsets.all(0),
iconSize: 20,
icon: Icon(
Icons.close,
),
onPressed: () => Navigator.pop(context),
),
if (!widget.hideSearch)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: TextField(
style: widget.searchStyle,
decoration: widget.searchDecoration,
onChanged: _filterElements,
),
),
],
),
children: [
Container(
width: widget.size?.width ?? MediaQuery.of(context).size.width,
height:
widget.size?.height ?? MediaQuery.of(context).size.height * 0.7,
child: ListView(
children: [
widget.favoriteElements.isEmpty
? const DecoratedBox(decoration: BoxDecoration())
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...widget.favoriteElements.map(
(f) => SimpleDialogOption(
child: _buildOption(f),
onPressed: () {
_selectItem(f);
},
),
),
const Divider(),
],
),
if (filteredElements.isEmpty)
_buildEmptySearchWidget(context)
else
...filteredElements.map(
(e) => SimpleDialogOption(
key: Key(e.toLongString()),
child: _buildOption(e),
onPressed: () {
_selectItem(e);
},
),
),
],
),
),
],
);
Widget _buildOption(CountryCode e) {
return Container(
width: 400,
child: Flex(
direction: Axis.horizontal,
children: <Widget>[
if (widget.showFlag)
Flexible(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Image.asset(
e.flagUri,
package: 'country_code_picker',
width: widget.flagWidth,
),
),
),
Expanded(
flex: 4,
child: Text(
widget.showCountryOnly
? e.toCountryStringOnly()
: e.toLongString(),
overflow: TextOverflow.fade,
style: widget.textStyle,
),
),
],
),
);
}
Widget _buildEmptySearchWidget(BuildContext context) {
if (widget.emptySearchBuilder != null) {
return widget.emptySearchBuilder(context);
}
return Center(
child: Text('No country found'),
);
}
#override
void initState() {
filteredElements = widget.elements;
super.initState();
}
void _filterElements(String s) {
s = s.toUpperCase();
setState(() {
filteredElements = widget.elements
.where((e) =>
e.code.contains(s) ||
e.dialCode.contains(s) ||
e.name.toUpperCase().contains(s))
.toList();
});
}
void _selectItem(CountryCode e) {
Navigator.pop(context, e);
}
}
Also filed an issue on the flutter github https://github.com/flutter/flutter/issues/59886
Edit:
I have a video of it right here
https://www.youtube.com/watch?v=669KitFG9ek&feature=youtu.be
I just had to remove the keys, so there probably was a duplicate key
...filteredElements.map(
(e) => SimpleDialogOption(
//key: Key(e.toLongString()),
child: _buildOption(e),
onPressed: () {
_selectItem(e);
},
),
),

How to add custom widget when button is pressed

I used a couple other threads to create an app where you type in some text in a textfield and when you press the button a default container is added to a list with the text in one of the fields. However when I type the text and add the widget the text is changed for all entries instead of just for the one that was added. This is my code:
import 'dart:core';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int count = 0;
TextEditingController noteSend = TextEditingController();
#override
Widget build(BuildContext context) {
List<Widget> children = new List.generate(
count,
(int i) => new InputWidget(
i,
noteRec: noteSend.text,
));
return new Scaffold(
appBar: new AppBar(title: new Text('some title')),
body: Column(
children: <Widget>[
Container(
child: TextField(
controller: noteSend,
),
color: Colors.lightBlueAccent,
width: 150,
height: 50,
),
Expanded(
child: ListView(
children: children,
scrollDirection: Axis.vertical,
),
),
],
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
onPressed: () {
setState(() {
count = count + 1;
});
},
));
}
}
class InputWidget extends StatefulWidget {
final int index;
final String noteRec;
InputWidget(this.index, {Key key, this.noteRec}) : super(key: key);
#override
_InputWidgetState createState() => _InputWidgetState();
}
class _InputWidgetState extends State<InputWidget> {
#override
Widget build(BuildContext context) {
return new Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: <Widget>[
Column(
children: <Widget>[
Icon(
Icons.image,
size: 75,
)
],
),
Container(
margin: EdgeInsets.only(left: 80, right: 30),
child: Column(
children: <Widget>[
Text('Note'),
],
),
),
Column(
children: <Widget>[
Text("${widget.noteRec}"),
],
),
],
),
);
}
}
How can I make the Text different with every entry?
List<Widget> children = new List.generate(
count,
(int i) => new InputWidget(
i,
noteRec: noteSend.text,
));
In this code, you set the input text for all the elements in children. It's the reason all the entries are changed to the same text. You can save the text to a list of the string when you press the save button and call it in List.generate:
List<Widget> children = new List.generate(
count,
(int i) => new InputWidget(
i,
noteRec: listString[i],
));
Try this code
Container(
height: 200,
child: Column(
children: <Widget>[
Expanded(
child: buildGridView(),
)
],
),
),
Then call the buildGridView that will return Widgets
Widget buildGridView() {
return Text('text here'); // your future widget
}

How to make Toggle Selected Image in Flutter?

I've tried several tutorials to create layouts like this, but they always fail.
maybe someone can help here
Can you please elaborate a bit more? As far as I know there is no direct way to make this. What you would need is to have a variable selectedImageIndex and you would have 2 "images" for each image, one that is highlighted and one that isn't and then you would write something like
child: selectedImageIndex == 1? HighlightedImage():NonHighLightedImage
and each image would be wrapped with a Gesture Detector so that when you tap it the selectedImageIndex changes. But again, that would mean that you have both versions of the image (or you have to manually somehow highlight it, or if it's an icon perhaps change color of icon. Please do provide more details
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(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selected;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.school),
color: (selected != null && selected == 0)
? Colors.blue
: Colors.grey,
onPressed: () {
setState(() {
selected = 0;
});
},
),
IconButton(
icon: Icon(Icons.school),
color: (selected != null && selected == 1)
? Colors.blue
: Colors.grey,
onPressed: () {
setState(() {
selected = 1;
});
},
)
],
),
),
);
}
}
Do let me know if it didn't work.
int _selectedA = 1, _selectedB = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildCircleA(icon: Icons.bluetooth, selection: 1),
_buildCircleA(icon: Icons.bluetooth_disabled, selection: 2),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildCircleB(icon: Icons.mail, selection: 1),
_buildCircleB(icon: Icons.mail_outline, selection: 2),
],
)
],
),
),
);
}
Widget _buildCircleA({IconData icon, int selection}) {
return GestureDetector(
onTap: () => setState(() => _selectedA = selection),
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: _selectedA == selection ? Colors.blue : Colors.transparent, width: 2),
),
child: Icon(icon, size: 56, color: _selectedA == selection ? Colors.blue : null),
),
);
}
Widget _buildCircleB({IconData icon, int selection}) {
return GestureDetector(
onTap: () => setState(() => _selectedB = selection),
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: _selectedB == selection ? Colors.blue : Colors.transparent, width: 2),
),
child: Icon(icon, size: 56, color: _selectedB == selection ? Colors.blue : null),
),
);
}