I have created a new flutter project and added the test package into my pubspec.yaml. Everytime I try to run my test, it fails with an error.
Here is the error message:
Here is the test code i'm trying to run:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:boringapp/main.dart';
void main() {
testWidgets('Clicking on tile expands it', (WidgetTester tester) async {
await tester.pumpWidget(MyApp());
expect(find.byIcon(Icons.launch), findsNothing);
await tester.tap(find.byType(ExpansionTile));
await tester.pump();
expect(find.byIcon(Icons.launch), findsOneWidget);
});
}
Here is my pubspec.yaml
name: boringapp
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
url_launcher: ^5.4.11
dev_dependencies:
test: 1.14.7
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
Here is my flutter doctor:
I am not even able to run the default test which comes when you create a new project. What am I missing?
Here is my homescreen.dart file
import 'package:boringapp/src/article.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Article> _articles = aritcles;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Home Page'),
),
body: RefreshIndicator(
onRefresh: () async {
setState(() {
_articles.removeAt(0);
});
return;
},
child: ListView(
children: _articles
.map((item) => ExpansionTile(
title: Text(item.title),
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text("comments"),
IconButton(
icon: Icon(Icons.open_in_new),
onPressed: () async {
if (await canLaunch(item.url)) {
launch(item.url);
}
},
)
],
)
],
))
.toList(),
),
),
);
}
}
Related
I have a problem with displaying the string output in Flutter App, I wanted to display the string value in column like this:
I
want
to
split
this
but instead I got this output:
[I, want, to, split, this]
I don't know what to do anymore as I am still new to programming, but I think this code below must be the cause:
void _splitWordInColumn(){
setState(() {
sentenceToWord.forEach((e) => print(e));
});
}
This is the image of that wrong output and below is my full code:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> sentenceToWord = 'I want to split this'.split(" ");
void _splitWordInColumn(){
setState(() {
sentenceToWord.forEach((e) => print(e));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo HomePage'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(sentenceToWord.toString()),
],
),
),
);
}
}
I hope someone can help me fix this, Thank you.
Try to use map operator with the column.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: sentenceToWord.map((e) => Text(e)).toList(),
),
Try this :
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String sentenceToWord = 'I \nwant \nto \nsplit \nthis';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo HomePage'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(sentenceToWord),
],
),
),
);
}
}
Is it possible to programmatically hide or close a window (not minimize), but still keep the process alive? This is similar to the hide()/show() methods in Qt and this is the standard approach in order to minimize the app to the tray.
window_manager is support show & hide window. you can try this.
https://github.com/leanflutter/window_manager
The package window_manager suggested by lijy91 didn't work out for me, because it did not work with Wayland under Fedora 36. It works perfectly on X11.
For now, I have decided to use bitsdojo_window combined with system_tray. It is definitely more than "just a window manager", but it works on my systems including Windows and MacOS.
A perfect example is already given on the example page of system_tray:
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart' hide MenuItem;
import 'package:system_tray/system_tray.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
doWhenWindowReady(() {
final win = appWindow;
const initialSize = Size(600, 450);
win.minSize = initialSize;
win.size = initialSize;
win.alignment = Alignment.center;
win.title = "How to use system tray with Flutter";
win.show();
});
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final SystemTray _systemTray = SystemTray();
final AppWindow _appWindow = AppWindow();
Timer? _timer;
bool _toogleTrayIcon = true;
#override
void initState() {
super.initState();
initSystemTray();
}
#override
void dispose() {
super.dispose();
_timer?.cancel();
}
Future<void> initSystemTray() async {
String path =
Platform.isWindows ? 'assets/app_icon.ico' : 'assets/app_icon.png';
List<String> iconList = ['darts_icon', 'gift_icon'];
final menu = [
MenuItem(label: 'Show', onClicked: _appWindow.show),
MenuItem(label: 'Hide', onClicked: _appWindow.hide),
MenuItem(
label: 'Start flash tray icon',
onClicked: () {
debugPrint("Start flash tray icon");
_timer ??= Timer.periodic(
const Duration(milliseconds: 500),
(timer) {
_toogleTrayIcon = !_toogleTrayIcon;
_systemTray.setImage(_toogleTrayIcon ? "" : path);
},
);
},
),
MenuItem(
label: 'Stop flash tray icon',
onClicked: () {
debugPrint("Stop flash tray icon");
_timer?.cancel();
_timer = null;
_systemTray.setImage(path);
},
),
MenuSeparator(),
SubMenu(
label: "Test API",
children: [
SubMenu(
label: "setSystemTrayInfo",
children: [
MenuItem(
label: 'setTitle',
onClicked: () {
final String text = WordPair.random().asPascalCase;
debugPrint("click 'setTitle' : $text");
_systemTray.setTitle(text);
},
),
MenuItem(
label: 'setImage',
onClicked: () {
String iconName = iconList[Random().nextInt(iconList.length)];
String path = Platform.isWindows
? 'assets/$iconName.ico'
: 'assets/$iconName.png';
debugPrint("click 'setImage' : $path");
_systemTray.setImage(path);
},
),
MenuItem(
label: 'setToolTip',
onClicked: () {
final String text = WordPair.random().asPascalCase;
debugPrint("click 'setToolTip' : $text");
_systemTray.setToolTip(text);
},
),
MenuItem(
label: 'getTitle [macOS]',
onClicked: () async {
String title = await _systemTray.getTitle();
debugPrint("click 'getTitle' : $title");
},
),
],
),
MenuItem(label: 'disabled Item', enabled: false),
],
),
MenuSeparator(),
MenuItem(
label: 'Exit',
onClicked: _appWindow.close,
),
];
// We first init the systray menu and then add the menu entries
await _systemTray.initSystemTray(
title: "system tray",
iconPath: path,
toolTip: "How to use system tray with Flutter",
);
await _systemTray.setContextMenu(menu);
// handle system tray event
_systemTray.registerSystemTrayEventHandler((eventName) {
debugPrint("eventName: $eventName");
if (eventName == "leftMouseDown") {
} else if (eventName == "leftMouseUp") {
_appWindow.show();
} else if (eventName == "rightMouseDown") {
} else if (eventName == "rightMouseUp") {
_systemTray.popUpContextMenu();
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: WindowBorder(
color: const Color(0xFF805306),
width: 1,
child: Row(
children: const [
LeftSide(),
RightSide(),
],
),
),
),
);
}
}
const backgroundStartColor = Color(0xFFFFD500);
const backgroundEndColor = Color(0xFFF6A00C);
class LeftSide extends StatelessWidget {
const LeftSide({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SizedBox(
width: 200,
child: Container(
color: const Color(0xFFFFFFFF),
child: Column(
children: [
WindowTitleBarBox(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [backgroundStartColor, backgroundEndColor],
stops: [0.0, 1.0]),
),
child: MoveWindow(),
),
),
Expanded(
child: Container(),
)
],
),
),
);
}
}
class RightSide extends StatelessWidget {
const RightSide({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: const Color(0xFFFFFFFF),
child: Column(
children: [
WindowTitleBarBox(
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [backgroundStartColor, backgroundEndColor],
stops: [0.0, 1.0]),
),
child: Row(
children: [
Expanded(
child: MoveWindow(),
),
const WindowButtons()
],
),
),
),
],
),
),
);
}
}
final buttonColors = WindowButtonColors(
iconNormal: const Color(0xFF805306),
mouseOver: const Color(0xFFF6A00C),
mouseDown: const Color(0xFF805306),
iconMouseOver: const Color(0xFF805306),
iconMouseDown: const Color(0xFFFFD500));
final closeButtonColors = WindowButtonColors(
mouseOver: const Color(0xFFD32F2F),
mouseDown: const Color(0xFFB71C1C),
iconNormal: const Color(0xFF805306),
iconMouseOver: Colors.white);
class WindowButtons extends StatelessWidget {
const WindowButtons({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Row(
children: [
MinimizeWindowButton(colors: buttonColors),
MaximizeWindowButton(colors: buttonColors),
CloseWindowButton(colors: closeButtonColors),
],
);
}
}
There are currently no Flutter APIs for controlling windows from Dart code. You would need to write native code to hide the window for the platform(s) you are interested in, and call it from Dart via platform channels.
As soon as I press the button I get the error code "Navigator operation requested with a context that does not include a Navigator." Code im using to navigate is in the RegisterPage and by the builder function should be displaying the MainPage.
void main() => runApp(RegisterPage());
class RegisterPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Register Your Account'),
centerTitle: true,
backgroundColor: Colors.green,
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.of(context)
.push(
MaterialPageRoute(
builder: (context) => MainPage()
),
);
},
child: Text('Sign in as guest'),
)),
)
);
}
}
class MainPage extends StatefulWidget{
String get title => "Cykla i stockholm";
MapPage createState()=> MapPage();
}
That's because the widget which uses the navigator (RegisterPage) is at the same level in the widget tree with the widget which creates the navigator(MaterialApp)
SOLUTION:
make the RegisterPage below MaterialApp in order to be able to use its context:
class RegisterPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Register Your Account'),
centerTitle: true,
backgroundColor: Colors.green,
),
body: Builder(
builder: (ctx)=> Center(//this context here has access to Navigator
child: RaisedButton(
onPressed: () {
Navigator.of(ctx)
.push(
MaterialPageRoute(
builder: (context) => MainPage()
),
);
},
child: Text('Sign in as guest'),
)),
),
)
);
}
}
I am a newbie to flutter, I am having a problem with passing the data to my search delegate class. The problem is that I have two tabs and I want to search within the active tab. So I am trying to send a variable that tells which tab is it and which table to look for value.
Here is what my code looks like:
class HomePage extends StatefulWidget {
static final String routeName = 'home';
#override
State<StatefulWidget> createState() {
return new _HomePageState();
}
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
var activeTab = "activity";
var _authToken, _id, _name, _emails, _userImage;
#override
void initState() {
super.initState();
tabController = TabController(vsync: this, length: 2)..addListener(() {
setState(() {
switch (tabController.index) {
case 0:
activeTab = "activity";
break;
case 1:
activeTab = "subparticipants";
break;
}
});
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
// appBar: new AppBar(
// title: Text('Dashboard'),
// ),
body: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
labelColor: Color(0xFFFFFFFF),
indicatorSize: TabBarIndicatorSize.tab,
tabs: [
//Tab(icon: Icon(Icons.directions_car)),
Tab(
text: "Activity Zone",
),
Tab(
text: "Sub Participant",
)
],
controller: tabController,
),
title: Text(
'Dashboard',
style: new TextStyle(
color: const Color(0xFFFFFFFF),
fontSize: 20.0,
fontWeight: FontWeight.w600,
letterSpacing: 0.3,
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(context: context, delegate: DataSearch(activeTab));
},
)
],
),
body: TabBarView(
controller: tabController,
children: [
TabActivity(),
TabSubparticipant(),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
print(
'Current Index: $activeTab');
},
),
drawer: _buildDrawer(context),
),
),
);
}
}
class DataSearch extends SearchDelegate{
final String activeTab;
DataSearch(this.activeTab);
#override
List<Widget> buildActions(BuildContext context){
return [
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: (){
query=activeTab;
},
)
];
}
#override
Widget buildLeading(BuildContext context) => IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.of(context).pop(),
);
#override
Widget buildResults(BuildContext context) => Text('Result');
#override
Widget buildSuggestions(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Search by job id, asset name, client name $query',
style: new TextStyle(
color: Colors.black, fontWeight: FontWeight.bold, fontSize: 22.0),
),
);
}
}
When I try to get $activeTab and show it in query or somewhere else, It just gives out the error:
flutter: The following assertion was thrown building _SearchPage<dynamic>(dirty, dependencies:
flutter: [_LocalizationsScope-[GlobalKey#a02e3], _InheritedTheme], state: _SearchPageState<dynamic>#eceaa):
flutter: 'package:flutter/src/widgets/basic.dart': Failed assertion: line 6173 pos 15: 'child != null': is
I am a bit confused how should I pass value to it. I have seen some of similar questions but they are no help. Like this or this question. None of these have any of these errors. Can you please let me know what am I doing wrong. Whats the issue? Please help.
Well, For someone who dumb as me and is having the same problem as I am, Here is how you can fix the issue,
So I was not passing the correct value to Search delegate and was not picking it up properly. Here is the fixed part of code
class DataSearch extends SearchDelegate {
DataSearch({
#required this.activeTab,
});
final activeTab;
#override
Widget buildResults(BuildContext context) {
if (activeTab == "subparticipants") {
...... .
....
..
My app runs perfectly on my device, however, on the log messages, I get an error that suggests that a pageView is needed.
This is the error I get when I swipe.
So I was hoping someone could help me sort out these errors I keep getting every time I swipe on my device
void main()
{
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(new MyApp());
});
}
class MyApp extends StatelessWidget
{
#override
Widget build(BuildContext context)
{
final tabController = new DefaultTabController(
length: 4 ,
child: new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.lightGreen,
title: new Text("Discover Zambia"),
bottom: new TabBar(
indicatorColor: Colors.red,
indicatorWeight: 4.0,
tabs: [
new Tab(icon: new Icon(Icons.home),text: "Home"),
new Tab(icon: new Icon(Icons.landscape),text: "Sights"),
new Tab(icon: new Icon(Icons.local_drink),text: "Nightlife"),
new Tab(icon: new Icon(Icons.restaurant),text: "Foods")
]),
),
body: new TabBarView(
children: [
new Home(),
new Sights(),
new Nightlife(),
new Foods()
]
),
));
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: "",
home: tabController,
);
}
}