Import Packages are not working/red underline. (Flutter) (Dart) - flutter
trying to use some packages and for some reason they aren't working/I am getting a red underline on each of them. Any answer on why this could be happening? as well as if there is a solution that could be provided, that would be much appreciated! I am new to this all and still learning!
For this set of code, the ones that are underlined would be
the logger package, dio package, and units package.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:simple_gradient_text/simple_gradient_text.dart';
import '../utils/dreams_utils.dart';
class ResourcesPage extends StatefulWidget{
#override
_ResourcesPageState createState() => _ResourcesPageState();
}
class _ResourcesPageState extends State<ResourcesPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: GradientText('Sleep Resources',
style: TextStyle(fontSize: 30.0,),
colors: [colorStyle("gradient1"), colorStyle("gradient2"),
colorStyle("gradient3"), colorStyle("gradient2"),
colorStyle("gradient1")]
),
backgroundColor: colorStyle("appHeader"),
),
backgroundColor: colorStyle("appBackground"),
resizeToAvoidBottomInset: true,
body: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/SleepF.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Sleep Foundation',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.sleepfoundation.org/sleep-hygiene/healthy-sleep-tips')
),
),
Text('We work hard to bring you the most accurate and up-to-date information about different sleep health topics. Rest assured every Sleep Foundation guide is carefully vetted and fact-checked prior to publication.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/IFFA.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('International Functional Foods Association',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://iffassociation.org/learn/how-functional-foods-may-improve-sleep-and-immune-health?gclid=Cj0KCQiAys2MBhDOARIsAFf1D1eHFvfuovsyweVETX8I5DOztdqM_QmIN_1DjOtkDNOiKlHIn9RN1bAaAhsLEALw_wcB')
),
),
Text('We exist to ensure everyone, everywhere has an equal chance to take control of their own health and wellness. Functional foods are an important component of healthy, nutritious diets. A diet rich in functional foods promotes a healthy body, as well as a healthy mind.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/Kaiser.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Kaiser Permanente',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://healthengagement.kaiserpermanente.org/wellness-topics/sleep/')
),
),
Text('We help people reach their health goals, by listening, supporting and guiding, so they can live their best lives.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/JHM.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('John Hopkins Medical',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.hopkinsmedicine.org/health/wellness-and-prevention/sleep')
),
),
Text('At Johns Hopkins Medicine, your health and safety are our very highest priorities. We are ready to care for you and your family in our hospitals, surgery centers, and through in-person clinic and online video visits. Learn how we are keeping you safe and protected so that you can get the care you need.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/BMI.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Beautiful Mind International',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://beauty-mind.org/sleep-guru/?gclid=Cj0KCQiAys2MBhDOARIsAFf1D1czPDb4ROkA_dhket7YAZrPB9H7AK4OqEclcbTaiU_OgDq9odhQ7x8aAhz7EALw_wcB')
),
),
Text('Beautiful Mind International project aims to educate people what is mental health, its issues, and ways to overcome them.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/CDC.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Centers for Disease Control and Prevention',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.cdc.gov/sleep/index.html')
),
),
Text('The Centers for Disease Control and Prevention is the national public health agency of the United States.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/sleepnum1.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Sleep Number',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.sleepnumber.com/categories/beds-on-sale?acid=psnonbrand&ascid=Google%2BNational-_-google-_-NB_Number_Bed-_-Number_Bed_Exact-_-516451220073-_-b-_-kwd-846217698-_-mediacode-_-Beds-_-1&key=number%20beds&s_kwcid=AL!6200!3!516451220073!b!!g!!number%20beds&k_clickid=go_cmp-193921164_adg-14393203044_ad-516451220073_kwd-846217698_dev-c_ext-_prd-&gclid=Cj0KCQiAys2MBhDOARIsAFf1D1d4C7oDgf9l_gikrEEVbK2Y7EpcHjg8AvPAmFGam3Qgjgc-XknDyYYaAtNfEALw_wcB')
),
),
Text('Sleep Number is an American manufacturer that makes the Sleep Number and Comfortaire beds, as well as foundations and bedding accessories. The company is based in Minneapolis, Minnesota. In addition to its Minnesota headquarters, Sleep Number has manufacturing and distribution facilities in South Carolina and Utah.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/sunset.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('UMN Duluth Health Services',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://health-services.d.umn.edu/health-education/sleep-education-initiatives')
),
),
Text('Health Education Staff, Interns, and our previous student health advisory committee developed and administered an informal needs assessment to measure student reported barriers to sleep and methods for sleep support that students would use. We learned a lot and are putting that information into practice with a series of initiatives on campus.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
],
),
),
);
}
}
For this set of code, the ones that are underlined in red would be the
units package, dio package, and logger package.
import 'package:flutter/material.dart';
import 'package:units/dreams/utils/dreams_constant.dart';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:dio/dio.dart';
import "package:units/api.dart";
List<dynamic> calculator(double hour, double minute, double sleepHour, double
sleepMinute,
UnitType uniType, UnitType unitTypeTime) {
List result = new List.filled(3, null, growable: false);
double tempHour = 0.0;
double tempMinute = 0.00;
if(uniType == UnitType.BED) {
tempHour = hour + sleepHour;
tempMinute = minute + sleepMinute;
if (tempMinute >= 60) {
tempMinute -= 60;
tempHour += 1;
}
}
if (uniType == UnitType.WAKE) {
tempHour = hour - sleepHour;
tempMinute = minute - sleepMinute;
if(tempMinute < 0){
tempMinute += 60.00;
tempHour -= 1;
}
}
if(tempHour > 12 || tempHour < 0) {
switch(unitTypeTime) {
case UnitType.AM: { unitTypeTime = UnitType.PM; }
break;
case UnitType.PM: { unitTypeTime = UnitType.AM; }
break;
default: {}
break;
}
tempHour %= 12;
}
if(tempHour ==0){
tempHour = 12;
}
//result = tempHour + (tempMinute/100);
result[0] = (tempHour + (tempMinute/100));
result[1] = unitTypeTime;
result[2] = uniType;
return result;
}
bool isEmptyString(String string){
return string == null || string.length == 0;
}
Future<int> loadValue() async{
SharedPreferences preferences = await SharedPreferences.getInstance();
int? data = preferences.getInt('data');
if( data != null ) {
return data;
} else {
return 0;
}
}
void saveValue(int value) async{
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setInt('data', value);
}
void setThemeKey(int color) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('theme', color);
}
Future<int?> getThemeKey() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final color = prefs.getInt('theme');
return color;
}
void setTheme(int theme){
switch(theme) {
case 1: { defaultTheme(); }
break;
case 2: { monochromeTheme(); }
break;
case 3: { pinkTheme(); }
break;
case 4: { sherbetTheme(); }
break;
case 5: { thunderTheme(); }
break;
case 6: { redTheme(); }
break;
case 7: { transTheme(); }
break;
case 8: { enbyTheme(); }
break;
default: { defaultTheme(); }
break;
}
}
Color mains = Colors.white60;
Color accent = Colors.cyan;
Color widgets = Colors.blueGrey.shade700;
Color gradient1 = Colors.cyan.shade900;
Color gradient2 = Colors.cyan.shade700;
Color gradient3 = Colors.cyan.shade500;
Color appHeader = Colors.blueGrey.shade900;
Color appBackground = Colors.blueGrey.shade800;
Future<int> defaultTheme() async {
mains = Colors.white60;
accent = Colors.cyan;
widgets = Colors.blueGrey.shade700;
gradient1 = Colors.cyan.shade900;
gradient2 = Colors.cyan.shade700;
gradient3 = Colors.cyan.shade500;
appHeader = Colors.blueGrey.shade900;
appBackground = Colors.blueGrey.shade800;
return 1;
}
Future<int> monochromeTheme() async {
mains = Colors.black;
accent = Colors.grey.shade700;
widgets = Colors.grey;
gradient1 = Colors.grey.shade700;
gradient2 = Colors.grey.shade500;
gradient3 = Colors.grey.shade300;
appHeader = Colors.grey.shade900;
appBackground = Colors.grey.shade800;
return 1;
}
Future<int> pinkTheme() async {
mains = Colors.pink.shade500;
accent = Colors.pink;
widgets = Colors.pink.shade200;
gradient1 = Colors.pinkAccent.shade700;
gradient2 = Colors.pinkAccent.shade400;
gradient3 = Colors.pinkAccent;
appHeader = Colors.pink.shade900;
appBackground = Colors.pink.shade800;
return 1;
}
Future<int> sherbetTheme() async {
mains = Colors.deepOrange;
accent = Colors.green.shade300;
widgets = Colors.yellow.shade100;
gradient1 = Colors.purpleAccent.shade400;
gradient2 = Colors.orangeAccent.shade100;
gradient3 = Colors.cyanAccent;
appHeader = Colors.pink.shade300;
appBackground = Colors.pink.shade100;
return 1;
}
Future<int> thunderTheme() async {
mains = Colors.yellow;
accent = Colors.yellowAccent;
widgets = Colors.grey.shade700;
gradient1 = Colors.cyan.shade500;
gradient2 = Colors.yellow.shade700;
gradient3 = Colors.yellow.shade200;
appHeader = Colors.grey.shade900;
appBackground = Colors.grey.shade800;
return 1;
}
Future<int> redTheme() async {
mains = Colors.red.shade900;
accent = Colors.red.shade900;
widgets = Colors.white70;
gradient1 = Colors.red.shade900;
gradient2 = Colors.red.shade700;
gradient3 = Colors.red.shade500;
appHeader = Colors.grey.shade500;
appBackground = Colors.grey.shade200;
return 1;
}
Future<int> transTheme() async {
mains = Colors.blue;
accent = Colors.pink;
widgets = Colors.white70;
gradient1 = Colors.lightBlue.shade200;
gradient2 = Colors.pinkAccent.shade100;
gradient3 = Colors.white;
appHeader = Colors.blue.shade800;
appBackground = Colors.pinkAccent.shade100;
return 1;
}
Future<int> enbyTheme() async {
mains = Colors.black;
accent = Colors.yellow.shade700;
widgets = Colors.white;
gradient1 = Colors.black;
gradient2 = Colors.yellow;
gradient3 = Colors.white;
appHeader = Colors.purple;
appBackground = Colors.purple.shade200;
return 1;
}
Color colorStyle(String color){
switch(color){
case "main":
return mains;
case "accent":
return accent;
case "widgets":
return widgets;
case "gradient1":
return gradient1;
case "gradient2":
return gradient2;
case "gradient3":
return gradient3;
case "appHeader":
return appHeader;
case "appBackground":
return appBackground;
default:
return Colors.purpleAccent;
}
}
This is the error code that I am getting
Invalid depfile: C:\Users\Mahjur - Coding\Desktop\SweetDreams-X.2.dart_tool\flutter_build\e98d11342ddd14555bbca12c2fd83e4a\kernel_snapshot.d
Invalid depfile: C:\Users\Mahjur - Coding\Desktop\SweetDreams-X.2.dart_tool\flutter_build\e98d11342ddd14555bbca12c2fd83e4a\kernel_snapshot.d
Error: Couldn't resolve the package 'logger' in 'package:logger/logger.dart'.
Error: Couldn't resolve the package 'dio' in 'package:dio/dio.dart'.
lib/dreams/utils/dreams_utils.dart:7:8: Error: Not found: 'package:logger/logger.dart'
import 'package:logger/logger.dart';
^
lib/dreams/utils/dreams_utils.dart:8:8: Error: Not found: 'package:dio/dio.dart'
import 'package:dio/dio.dart';
^
lib/dreams/utils/dreams_utils.dart:9:8: Error: Error when reading 'lib/api.dart': The system cannot find the file specified.
import "package:units/api.dart";
^
Here is my pubspec.yaml
name: units
description: A new Flutter project.
# The following line prevents the package from being accidentally
published to
# pub.dev using `pub publish`. This is preferred for private
packages.
publish_to: 'none' # Remove this line if you wish to publish to
pub.dev
# The following defines the version and build number for your
application.
# A version number is three numbers separated by dots, like
1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in
flutter
# build by specifying --build-name and --build-number,
respectively.
# In Android, build-name is used as versionName while build-
number used as versionCode.
# Read more about Android versioning at
https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while
build-number used as CFBundleVersion.
# Read more about iOS versioning at
#
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.6
# The following adds the Cupertino Icons font to your
application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_core: ^1.13.1
firebase_auth: ^3.3.11
cloud_firestore: ^3.1.10
modal_progress_hud: ^0.1.3
firebase_messaging: ^11.2.11
firebase_analytics: ^9.1.2
flutter_launcher_icons: ^0.9.2
flutter_local_notifications: ^9.4.0
#flutter_native_timezone: ^1.1.0
rxdart: ^0.27.1
#awesome_notifications: ^0.6.21
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see
the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons
in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section,
like
this:
assets:
- lib/assests/images/
- android/app/src/main/res/drawable/
# -lib/dreams/images/app_icon.png
# An image asset can refer to one or more resolution-specific
"variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package
dependencies,
see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section
here,
# in this "flutter" section. Each entry in this list should
have a
# "family" key with the font family name, and a "fonts" key
with a
# list giving the asset and other descriptors for the font.
For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
run in the command line
flutter clean
then
flutter pub get
if that doesn't help, shut down and restart android studio and the file.
if that doesn't help delete the dependency from the pubspec.yaml run pub get, then re-add the dependency and run pub get, sometimes you have to hit flutter over the head with a hammer.
double check the packages you are having issues with are actually added in the pubspec.yaml and ensure there is not a # infront of them that comments them out
Related
flutter_markdown custom widget always on its own line
I'm using the flutter markdown package made by the flutter team here https://pub.dev/packages/flutter_markdown. I've created my own MarkdownElementBuilder based on their examples that inserts my own custom widget into the markdown and it looks like this: import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:outlit_app/constants/color_theme.dart'; import 'package:outlit_app/constants/dimension.dart'; import 'package:outlit_app/models/models.dart'; import 'package:markdown/markdown.dart' as md; class DefinitionBuilder extends MarkdownElementBuilder { final List<Definition> definitions; DefinitionBuilder(this.definitions) : super(); #override Widget visitElementAfter(md.Element element, TextStyle preferredStyle) { final String textContent = element.textContent; Definition definition = definitions.firstWhere( (def) => textContent.toLowerCase().contains(def.word.toLowerCase()), orElse: () => Definition(word: 'nothing found for $textContent', definition: ''), ); return Tooltip( margin: EdgeInsets.all(Dimensions.MARGIN_SIZE_EXTRA_LARGE), padding: EdgeInsets.all(Dimensions.PADDING_SIZE_DEFAULT), decoration: BoxDecoration( color: GetColor.gradientPurple, borderRadius: BorderRadius.circular(8), ), verticalOffset: -10, triggerMode: TooltipTriggerMode.tap, message: definition.definition.trim(), child: Text( textContent.trim(), style: TextStyle( color: GetColor.primaryColor, fontSize: Dimensions.FONT_SIZE_OVER_LARGE, ), ), ); } } class DefinitionSyntax extends md.InlineSyntax { static final String AST_SYMBOL = 'def'; DefinitionSyntax() : super(_pattern); static const String _pattern = r'{{(.*)}}'; #override bool onMatch(md.InlineParser parser, Match match) { parser.addNode(md.Element.text(AST_SYMBOL, match[1])); return true; } } It works well but the widget is always on it's own seperate line as opposed to being inline with the rest of the text. If I return a simple text widget I still get the same thing. Any tips in the right direction would be great :)
I got it work although not perfect because the leading distribution is a little off with the text of the tooltip but the widget that gets embedded now looks like this: return RichText( text: TextSpan( children: [ WidgetSpan( child: Container( child: Tooltip( margin: EdgeInsets.all(Dimensions.MARGIN_SIZE_EXTRA_LARGE), padding: EdgeInsets.all(Dimensions.PADDING_SIZE_DEFAULT), decoration: BoxDecoration( color: GetColor.gradientPurple, borderRadius: BorderRadius.circular(8), ), verticalOffset: -10, triggerMode: TooltipTriggerMode.tap, message: definition.definition.trim(), child: Text( textContent.trim(), style: TextStyle( color: GetColor.primaryColor, fontSize: Dimensions.FONT_SIZE_OVER_LARGE, leadingDistribution: TextLeadingDistribution.even, height: 1, ), ), ), )) ], ), );
how to make a button at the bottom of the drop down list
to create the popup list i used dropdown_search design example as I would like to see it when I start searching through the elements of the list, a button for adding should pop up or the button should be immediately when we start searching for the element drop-down list button bottom I chose all possible methods in the library, but still I can't use it with the addition of a button all code https://github.com/dimapichuev2000/test_dropdownbutton main.dart import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:dropdown_search/dropdown_search.dart'; import 'package:test_dropdownbutton/gym_model.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().copyWith( primaryColor: Colors.amber, colorScheme: ThemeData().colorScheme.copyWith( primary: Colors.orange, ), ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } final String title; #override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final _multiKey = GlobalKey<DropdownSearchState<String>>(); Widget _customDropDownExample(BuildContext context, GymModel? item) { if (item == null) { return const Text( "Выберите фитнесс центр", style: TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)), ); } return Container( child: (item.avatar == "") ? ListTile( contentPadding: EdgeInsets.all(0), leading: const CircleAvatar( radius: 25, backgroundColor: Colors.white, backgroundImage: NetworkImage( 'https://img.icons8.com/ios/50/000000/gum-.png'), ), title: Text(item.gym), subtitle: Text( item.location, ), ) : ListTile( contentPadding: const EdgeInsets.all(0), leading: CircleAvatar( radius: 25, backgroundImage: NetworkImage(item.avatar ?? ''), ), title: Text(item.gym), subtitle: Text( item.location, ), ), ); } Widget _exitPopup(BuildContext context) { return Container( decoration: const BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), padding: const EdgeInsets.only(top: 2), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: EdgeInsets.all(8), height: 30, width: 30, ), const Text( "Фитнесс центр", style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500), ), IconButton( icon: Image.asset( 'assets/button_X.png', width: 25, height: 25, fit: BoxFit.fill, ), iconSize: 25, onPressed: () { Navigator.of(context).pop(); }, ) ], ), ); } Widget _customPopupItemBuilderExample( BuildContext context, GymModel? item, bool isSelected) { return Container( decoration: !isSelected ? null : BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white, ), child: ListTile( selected: isSelected, title: Text(item?.gym ?? ''), subtitle: Text(item?.location ?? ''), leading: (item!.avatar == "") ? const CircleAvatar( radius: 25, backgroundColor: Colors.white, backgroundImage: NetworkImage( 'https://img.icons8.com/ios/100/000000/gum-.png'), ) : CircleAvatar( radius: 25, backgroundImage: NetworkImage(item.avatar ?? ''), )), ); } #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Key value Pair - DropdownButton'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: SingleChildScrollView( child: DropdownSearch<GymModel>( mode: Mode.BOTTOM_SHEET, showSearchBox: true, compareFn: (item, selectedItem) => item?.id == selectedItem?.id, scrollbarProps:ScrollbarProps( radius: Radius.circular(20), thickness: 4, ), onFind: (String? filter) => getData(filter), dropdownSearchDecoration: const InputDecoration( filled: true, fillColor: Color(0xFFE3E3E4), hintText: "Выберите фитнесс центр", border: OutlineInputBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10), ), borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), contentPadding: EdgeInsets.fromLTRB(12, 3, 0, 0), ), popupSafeArea: const PopupSafeAreaProps(top: true, bottom: true), // labelText: "Выберите фитнесс центр ", onChanged: (data) { print(data); }, maxHeight: 850, dropdownBuilder: _customDropDownExample, popupItemBuilder: _customPopupItemBuilderExample, dropDownButton: Image.asset('assets/dropButton.png', color: Color(0xFF79818A)), popupTitle: _exitPopup(context), popupShape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), ), ), searchFieldProps: TextFieldProps( decoration: const InputDecoration( prefixIcon: Icon( Icons.search, ), filled: true, fillColor: Color(0xFFE3E3E4), border: OutlineInputBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10), ), borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), contentPadding: EdgeInsets.fromLTRB(12, 12, 8,0), // labelText: "Поиск", hintText: "Поиск", hintStyle: TextStyle(fontSize: 17)), ), ), ), ), ], ), ), ); } Future<List<GymModel>> getData(filter) async { var response = await Dio().get( "https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts", queryParameters: {"filter": filter}, ); final data = response.data; if (data != null) { return GymModel.fromJsonList(data); } return []; } } gym_model.dart class GymModel { final String id; final String location; final String gym; final String? avatar; GymModel( {required this.id, required this.location, required this.gym, this.avatar}); factory GymModel.fromJson(Map<String, dynamic> json) { return GymModel( id: json["id"], location: json["location"], gym: json["gym"], avatar: json["avatar"], ); } static List<GymModel> fromJsonList(List list) { return list.map((item) => GymModel.fromJson(item)).toList(); } #override String toString() => gym; } pubspec.yaml name: fitsupp_coach description: A new Flutter project. # The following line prevents the package from being accidentally published to # pub.dev using `flutter pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: sdk: ">=2.12.0 <3.0.0" # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions # consider running `flutter pub upgrade --major-versions`. Alternatively, # dependencies can be manually updated by changing the version numbers below to # the latest version available on pub.dev. To see which dependencies have newer # versions available, run `flutter pub outdated`. dependencies: flutter_localizations: sdk: flutter flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 pinput: ^1.2.2 intl: ^0.17.0 quiver: ^3.0.1+1 firebase_auth: ^3.3.5 firebase_core: ^1.11.0 dropdown_search: ^2.0.1 dio: ^4.0.4 provider: ^6.0.2 percent_indicator: ^4.0.0 dev_dependencies: flutter_test: sdk: flutter # The "flutter_lints" package below contains a set of recommended lints to # encourage good coding practices. The lint set provided by the package is # activated in the `analysis_options.yaml` file located at the root of your # package. See that file for information about deactivating specific lint # rules and activating additional ones. flutter_lints: ^1.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - assets/images/ - assets/images/DropDown/ # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: fonts: - family: SF Pro Display fonts: - asset: fontsassets/SFProDisplay/SFProDisplay-Light.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Medium.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Black.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Bold.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Heavy.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Regular.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Semibold.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Thin.ttf - asset: fontsassets/SFProDisplay/SFProDisplay-Ultralight.ttf style: normal - family: SF Pro Text fonts: - asset: fontsassets/SFProText/SF-Pro-Text-Light.otf - asset: fontsassets/SFProText/SF-Pro-Text-Medium.otf - asset: fontsassets/SFProText/SF-Pro-Text-Black.otf - asset: fontsassets/SFProText/SF-Pro-Text-Bold.otf - asset: fontsassets/SFProText/SF-Pro-Text-Heavy.otf - asset: fontsassets/SFProText/SF-Pro-Text-Regular.otf - asset: fontsassets/SFProText/SF-Pro-Text-Semibold.otf - asset: fontsassets/SFProText/SF-Pro-Text-Thin.otf - asset: fontsassets/SFProText/SF-Pro-Text-Ultralight.otf style: normal # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages flutter_intl: enabled: true
There are many ways you can do that but the easiest and the most elegant solution in my opinion is the following: Column( children: [ Flexible( child: ListView.builder( shrinkWrap: true, itemCount: 5, itemBuilder: (BuildContext context, int i) { return Text(i.toString()); }, ), ), ElevatedButton.icon( onPressed: null, icon: const Icon(Icons.abc), label: const Text('next')), ], ); Start with a Column widget and then add ListView.builder and button of your choosing, I use ElevatedButton.icon, as it's children. Now set the shrinkWrap setting in ListView.builder to true and finally wrap it with Flexible widget. In your case, you can wrap your Container widget with a ListView.builder widget and if you get viewport.dart error just wrap it with either Flexible or Expanded, depending on how much space you want it to consume. Then you can add logic to check if you are at the last index, in which case you can show your button, this is kinda what the code it will end up looking like: Flexible( child: ListView.builder( shrinkWrap: true, itemCount: _listSavedOutsideThisWidget.length+1, itemBuilder: (BuildContext context, int index) { if (index == _listSavedOutsideThisWidget.length) { return TextButton.icon( onPressed: _onPressed(context), icon: const Icon(Icons.upload_file), label: const Text('Upload Data')); } return Container( decoration: !isSelected ? null : BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white, ), child: ListTile( selected: isSelected, title: Text(item?.gym ?? ''), subtitle: Text(item?.location ?? ''), leading: (item!.avatar == "") ? const CircleAvatar( radius: 25, backgroundColor: Colors.white, backgroundImage: NetworkImage( 'https://img.icons8.com/ios/100/000000/gum-.png'), ) : CircleAvatar( radius: 25, backgroundImage: NetworkImage(item.avatar ?? ''), )), ); }, ), ); For this method to work you will have to create a List<GymModel> _listSavedOutsideThisWidget = [] variable outside the build function and populate it by changing the onFind method under DropdownSearch widget, like such: onFind: (String? filter) async { List<GymModel>> filteredList = await gedtData(filter); setState(() => _listSavedOutsideThisWidget = filteredList); // return getData(filter); return filteredList; // if this doesn't work, try uncommenting the above line } Hope this helps. Feel free to ask more questions.
OK, this may not be the most elegant solution, but it does the trick. First create a Model for the button: class BottomButton { final String? text; BottomButton({ this.text, }); } Then you are going to want to change all the output types from GymModel? to dynamic: Widget _customDropDownExample(BuildContext context, dynamic item) Widget _customPopupItemBuilderExample( BuildContext context, dynamic item, bool isSelected) DropdownSearch<dynamic> Future<List<dynamic>> getData(filter) Now, in the _customDropDownExample function where you are checking if the item == null add another to see if item is !GymModel: if (item == null || item is !GymModel) { return const Text( "Выберите фитнесс центр", style: TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)), ); } Inside _customPopupItemBuilderExample function check to see if the item is GymModel if so then do exactly what you were doing before and if not then create a button widget of your choice, I used an ElevatedButton for simplicity: if (item is GymModel) { return Container( decoration: !isSelected ? null : BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.white, ), child: ListTile( selected: isSelected, title: Text(item.gym), subtitle: Text(item.location), leading: (item.avatar == "") ? const CircleAvatar( radius: 25, backgroundColor: Colors.white, backgroundImage: NetworkImage("https://picsum.photos/200"), ) : CircleAvatar( radius: 25, backgroundImage: NetworkImage(item.avatar ?? ''), )), ); } else { return ElevatedButton(onPressed: () {}, child: Text(item.text)); } Also write an another function to filter the result and assign it to filterFn attribute in DropDownSearch widget: bool _filterItems(dynamic item, String? str) { if (item is GymModel) { return (item.gym.toLowerCase().contains(str!.toLowerCase()) || item.location.toLowerCase().contains(str.toLowerCase())); } return (item is BottomButton); } Finally inside getData function where you check if the data != null add your button model (BottomButton, in my case) to the list: Future<List<dynamic>> getData(filter) async { var response = await Dio().get( "https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts", queryParameters: {"filter": filter}, ); final data = response.data; if (data != null) { List<dynamic> res = GymModel.fromJsonList(data); BottomButton button = BottomButton(text: "Good Luck!"); return [...res, button]; } return []; }
flutter/getx how to initialize nullable obejct observable
let's say I have a controller like this: class ProfileController extends GetxController { Rx<UserFacebookInfo?> facebookInfo = null.obs; void facebookSync() async { // // logic to get user info from facebook // facebookInfo.value = UserFacebookInfo.fromFacebookApi(userData); // facebookInfo = UserFacebookInfo.fromFacebookApi(userData).obs; <=== also tried this update(); } } } and in widget I have something like this: Widget buildFacebook() => Padding( padding: const EdgeInsets.only(top: 30.0, right: 20.0, left: 20.0, bottom: 10.0), child: Obx(() => (_profileController.facebookInfo.value == null) ? Column( children: [ IconButton( icon : const Icon(Icons.facebook_outlined, size: 40.0), onPressed: () => _profileController.facebookSync() ), const Text( 'Facebook', style: TextStyle(color: Colors.white), ) ], ) : Column( children: [ UserProfileAvatar( avatarUrl: _profileController.facebookInfo.value!.facebookAvatar, radius: 40, ), Text( _profileController.facebookInfo.value!.name, style: const TextStyle(color: Colors.white), ) ], ) )); and because initial value nullable, it's not working and not changing widget on a fly, but only if I update it from android studio. What is the correct way to initialize it??? I had similar case with nullable string observable so I was able to initialize it lie String string (null as String?).obs` Thanks for any advice
You can initialize nullable observables by using Rxn<Type>(). Therefore use this: final facebookInfo= Rxn<UserFacebookInfo>();
AssetsAudioPlayer only plays the audio at last index
I'm using a listview to display images and text in my flutter app. I've stored the asset path and text in a Json file and I convert it to a list. Getting the image asset path and displaying the correct one seems to work with no issues but thats not the case in playing the audio files from their assets. I'm using this package import 'package:assets_audio_player/assets_audio_player.dart'; declaration final AssetsAudioPlayer playAudio = AssetsAudioPlayer(); and this is main widget #override Widget build(BuildContext context) { Widget _buildRow(int idx) { for (var translations in widget.category.translations) { _wordList = widget.category.translations[idx]; return Container( height: 88.0, child: Card( child: ListTile( onTap: () { playAudio.open( Audio(_wordList.audio), ); // player.play(_wordList.audio); log(_wordList.audio, name: 'my.other.category'); }, onLongPress: () {}, leading: SizedBox( width: 50.0, height: 88.0, child: Image( image: AssetImage(_wordList.emoji), fit: BoxFit.contain, ), ), title: Text( _wordList.akan, style: TextStyle(fontSize: 18), ), subtitle: Text( _wordList.english, style: TextStyle(fontSize: 18, color: Colors.black), ), trailing: const Icon(Icons.play_arrow, size: 28), ), ), ); } } Since the image assets in the json file have no issues I don't get why the audio does I've stored them like this, { "english": "mother", "akan": "ɛna", "emoji": "assets/icons/family_mother.png", "audio": "assets/audio/family_mother.mp3" },
Solved it by generating a new listtile widget through iteration and then putting it into a listview
Flutter passing list of strings in CupertinoPicker widget using loops
I was trying to pass a list inside CupertinoPicker using loops but I couldn't figure it this image contains the function I was trying to build const List<String> currenciesList = [ 'AUD', 'BRL', 'CAD', 'CNY', 'EUR', 'GBP', 'HKD', 'IDR', 'ILS', 'INR', 'JPY', 'MXN', 'NOK', ]; Container( height: 150.0, alignment: Alignment.center, padding: EdgeInsets.only(bottom: 30.0), color: Colors.lightBlue, child:CupertinoPicker( backgroundColor: Colors.lightBlue, itemExtent: 32.0, onSelectedItemChanged: (selectedIndex){ print(selectedIndex); }, children:[ Text('USD',style: whiteColor ), Text('EUR' , style: whiteColor), Text('GDP', style:whiteColor), ] ), ),
As of Dart 2.3 you can use Collection For: CupertinoPicker( children:[ for (String name in currenciesList) Text( name ,style: whiteColor ), ] )
You should create a Func to get all value in your list. List<Widget> getPickerItems() { List<Text> itemsCurrency = []; for (var currency in currenciesList) { itemsCurrency.add(Text(currency)); } return itemsCurrency; } and add it in to children of CupertinoPicker: CupertinoPicker( children: getPickerItems(), )