#StackBounty: #dart #flutter-test #rxdart Test stream with wrapped array

Bounty: 50

I’m trying to test that the function emitArray emits a Response.Success an its value is ['test'].
If I emit a List<String> everything works as expected, but once I wrap the result list in a Response<List<String>> the test fails.

The result is emitted, but it fails when comparing with the expected result.
I’m wondering if it’s related to the implementation of == in Response.Success, I’m using the default implementation that the IDE provides.

This is not the real code I have, it’s just a simple example that is easier to understand to try to identify the issue.

This is my class to test:

class ListResponse {
  final _array = BehaviorSubject<Response<List<String>>>();

  Stream<Response<List<String>>> get array => _array.stream;

  Future<void> emitArray() async {
    _array.add(Response.success(['test']));
  }

  void dispose() {
    _array.close();
  }
}

This is my test:

void main() {
  ListResponse underTest;
  setUp(() {
    underTest = ListResponse();
  });

  test('It should emit array', () {
    final array = Response.success(['test']);

    expect(
      underTest.array,
      emitsInOrder([
        array,
        emitsDone,
      ]),
    );

    underTest.emitArray();

    underTest.dispose();
  });
}

This is the error it throws:

Expected: should do the following in order:
          • emit an event that SuccessResponse<List<String>>:<SuccessResponse{value: [test]}>
          • be done
  Actual: <Instance of 'BehaviorSubject<Response<List<String>>>'>
   Which: emitted • SuccessResponse{value: [test]}
                  x Stream closed.
            which didn't emit an event that SuccessResponse<List<String>>:<SuccessResponse{value: [test]}>

This is the Response class

class Response<T> {
  Response._();

  factory Response.success(T value) = SuccessResponse<T>;
  factory Response.error(Exception error) = ErrorResponse<T>;
}

class ErrorResponse<T> extends Response<T> {
  ErrorResponse(this.error): super._();

  final Exception error;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is ErrorResponse &&
              runtimeType == other.runtimeType &&
              error == other.error;

  @override
  int get hashCode => error.hashCode;

  @override
  String toString() {
    return 'ErrorResponse{error: $error}';
  }
}

class SuccessResponse<T> extends Response<T> {
  SuccessResponse(this.value): super._();

  final T value;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is SuccessResponse &&
              runtimeType == other.runtimeType &&
              value == other.value;

  @override
  int get hashCode => value.hashCode;

  @override
  String toString() {
    return 'SuccessResponse{value: $value}';
  }
}


Get this bounty!!!

#StackBounty: #flutter #dart How to Add Dynamic table to Flutter

Bounty: 50

How to map existing values to a Flutter Dynamic Table?

The following is my existing working code. is using json to print the values. those existing values I would like to print to a table and eventually sort them by columns.
Note: New to Flutter and I appreciate your assistance.

class PhotosList extends StatelessWidget {
  final List<Photo> photos;

  PhotosList({Key key, this.photos}) : super(key: key);



  @override
  Widget build(BuildContext context) {


    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return ListTile(
          // leading: Icon(Icons.album),
          title: Column(  children: [
            Text(photos[index].symbol),
            Padding(padding: EdgeInsets.only(bottom: 10.0)),
            //Text(photos[index].companyName),

          ],
          ),
          subtitle: Column(


            children: [

              Text ('${photos[index].data["quote"]["companyName"] ?? ""}'),
              Text ("Dividend Yield:" '${photos[index].data["stats"]["dividendYield"] ?? ""}'),
              Text ("Last Price:" '${photos[index].data["quote"]["iexBidPrice"]?? ""}'),
              Text ("Last Price:" '${photos[index].data["stats"]["latestPrice"]?? ""}'),

              //


            ],
          ),
        );
      },
    );
  }
}

Data Table:
from: https://github.com/iampawan/FlutterWidgets/blob/master/lib/Episode5_DataTable/datatable_example.dart

Widget bodyData() => DataTable(
      onSelectAll: (b) {},
      sortColumnIndex: 1,
      sortAscending: true,
      columns: <DataColumn>[
        DataColumn(
          label: Text("First Name"),
          numeric: false,
          onSort: (i, b) {
            print("$i $b");
            setState(() {
              names.sort((a, b) => a.firstName.compareTo(b.firstName));
            });
          },
          tooltip: "To display first name of the Name",
        ),
        DataColumn(
          label: Text("Last Name"),
          numeric: false,
          onSort: (i, b) {
            print("$i $b");
            setState(() {
              names.sort((a, b) => a.lastName.compareTo(b.lastName));
            });
          },
          tooltip: "To display last name of the Name",
        ),
      ],
      rows: names
          .map(
            (name) => DataRow(
                  cells: [
                    DataCell(
                      Text(name.firstName),
                      showEditIcon: false,
                      placeholder: false,
                    ),
                    DataCell(
                      Text(name.lastName),
                      showEditIcon: false,
                      placeholder: false,
                    )
                  ],
                ),
          )
          .toList());

Thank you!
😊


Get this bounty!!!

#StackBounty: #android #flutter #dart Execution failed for task ':flutter_twitter:verifyReleaseResources'

Bounty: 100

I’m working on Flutter app. I can run app in the android device successfully but try to make build (.apk) file and got below issues.

FAILURE: Build failed with an exception.                                                                           

* What went wrong:                                                                                                 
Execution failed for task ':flutter_twitter:verifyReleaseResources'.                                               
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade                  
   > Android resource linking failed                                                                               
     /Users/ipatel/.gradle/caches/transforms-2/files-2.1/8f09fa5c6115de167b21b323f769edd9/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /Users/ipatel/.gradle/caches/transforms-2/files-2.1/8f09fa5c6115de167b21b323f769edd9/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.


* Try:                                                                                                             
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org                                                                         

BUILD FAILED in 5m 2s                                                                                              
Running Gradle task 'assembleRelease'...                                                                           
Running Gradle task 'assembleRelease'... Done                     303.8s (!)
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin firebase_messaging...
The plugin firebase_messaging could not be built due to the issue above.

Below are project’s stuffs

defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.xxxx.eeee"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

> local.properties

sdk.dir=/Users/ipatel/Library/Android/sdk
flutter.sdk=/Users/ipatel/Documents/Amit/FlutterSetup/flutter
flutter.buildMode=release
flutter.versionName=1.0.0
flutter.ver

My app is compatible with AndroidX and also tried with many solution but can’t able to fix my issue.

I checked
https://github.com/roughike/flutter_twitter_login/issues/29
A failure occurred while executing com.android.build.gradle.internal.tasks
flutter Error "Android dependency 'androidx.core:core' has different version" using flutter_local_notifications and location packages

and others.

Flutter Doctor Result:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.12.13+hotfix.6, on Mac OS X 10.14.3 18D109, locale en-IN)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 10.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.41.1)
[✓] Connected device (4 available)

~PS : Let me know if you want more details from my end.


Get this bounty!!!

#StackBounty: #flutter #dart #stack #pie-chart Pie-Chart flutter

Bounty: 50

I’m using pie_chart library to draw pie-chart in my flutter project.

Does anyone know how to add the text in the center of pie, and increase the arc width?

Edit

 return PieChart(
                              dataMap: dataMap,
                              animationDuration: Duration(milliseconds: 800),
                              chartRadius:
                                  MediaQuery.of(context).size.width / 1.7,
                              showChartValuesInPercentage: true,
                              showChartValues: true,
                              showChartValuesOutside: true,
                              chartValueBackgroundColor: Colors.grey[200],
                              colorList: colorList,
                              showLegends: true,
                              legendPosition: LegendPosition.right,
                              decimalPlaces: 1,
                              showChartValueLabel: true,
                              chartType: ChartType.ring,
                              centerText: "Title",
                            );


Get this bounty!!!

#StackBounty: #http #flutter #dart How to pass List of Custom Objects using Dart's http?

Bounty: 50

I am trying to pass List of Custom Object to my API.

Following is my code

import 'package:meta/meta.dart';
import 'package:json_annotation/json_annotation.dart';

part 'submit_survey_question_options_model.g.dart';

@JsonSerializable(nullable: false)
class SubmitSurveyQuestionOptionsModel {
  String questionId;
  String answer;

  SubmitSurveyQuestionOptionsModel(
      {@required this.questionId, @required this.answer});

  factory SubmitSurveyQuestionOptionsModel.fromJson(
          Map<String, dynamic> json) =>
      _$SubmitSurveyQuestionOptionsModelFromJson(json);

  Map<String, dynamic> toJson() =>
      _$SubmitSurveyQuestionOptionsModelToJson(this);
}



Future<SubmitSurveyModel> submitSurvey(
      String userId,
      String facultyId,
      String surveyId,
      List<SubmitSurveyQuestionOptionsModel> submitSurveyQuestionOptionList,
      String subjectId) async {
    Map<String, dynamic> body = {
      "userId": userId,
      "facultyId": facultyId,
      "surveyId": surveyId,
      "survey": submitSurveyQuestionOptionList,
      "subjectId": subjectId
    };

    final response = await http.post(
      SUBMIT_SURVEY_URL,
      body: json.encode(body),
    );

    SubmitSurveyModel submitSurveyModel = standardSerializers.deserializeWith(
        SubmitSurveyModel.serializer, json.decode(response.body));


    return submitSurveyModel;
  }

I am using json_serializable in my pubspec.
I built the serializable class using flutter packages pub run build_runner build

I am not able to figure out what’s the problem as the data is not submitted properly?

I have referred the following links but couldn’t get it working

Flutter Error: type 'AddressInfo' is not a subtype of type 'String' in type cast

Dart Error Converting Object To JSON


Get this bounty!!!

#StackBounty: #dart #flutter #inherited-widget ListView loses scroll position when using InheritedWidget in Flutter

Bounty: 50

After adding InheritedWidget to app I recognize that ListView loses scroll position (selected item index) when I come back to list from details screen using Pop().

I know that widget can be rebuild any time but maybe someone can suggest solution without handling cache manually.

P.S.
Scroll position was fine before implementing InheritedWidget


Get this bounty!!!

#StackBounty: #generics #design-patterns #data-structures #types #dart How to store a collection path for a model?

Bounty: 50

I’m building models for my app in Dart/Flutter. Here’s how a model looks like:

abstract class Model {
  /// A unique identifier of the model.
  /// Gets generated by Firestore.
  final String id;

  Model(this.id);
}

class MyModel extends Model {
  final String name;
  final String description;
  final int order;

  MyModel(String id, this.name, this.items, this.order) : super(id);
}

Those models would be stored in Google Firestore in mymodels collection:

mymodels/abc
mymodels/def
...

To fetch a list of these models from Firestore I need to store the collection path (mymodels) for MyModel type somewhere. So I could use it later when fetching models:

Future<List<T>> fetchList() {
  // How to know `path` by knowing T?
  _firestore.collection('path').getDocuments()
}

Where to store that collection path? I was thinking to declare a static property in Model interface, but Dart doesn’t seem to allow override static properties.

Would Dart annotations be a good fit for that?


Get this bounty!!!

#StackBounty: #android #dart #flutter #alarmmanager Android Alarm Manager is not working for Flutter Project App

Bounty: 50

I have installed the Android Alarm Manager plugin in my New Flutter app. I use the example code of Plugin- but it gives error in console.

Please suggest how to make android alarm manager plugins works.
How do I Integrate the Dart’s android_alarm_manager to the app so that users get alarm when the time they picked in the schedule reaches?

I use the code from this link:
https://github.com/flutter/plugins/tree/master/packages/android_alarm_manager

 //////  main.dart://///////

    import 'dart:isolate';
    import 'package:android_alarm_manager/android_alarm_manager.dart';
    import 'package:flutter/material.dart';

    void printHello() {
      final DateTime now = DateTime.now();
      final int isolateId = Isolate.current.hashCode;
      print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
    }
    void main() async {
      final int helloAlarmID = 0;
      await AndroidAlarmManager.initialize();
      runApp(MaterialApp(home: Application()));
      await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);
    }
    class Application extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(),
        );
      }
    }


///////////////Application.java/////////////////////

    package io.flutter.plugins.androidalarmmanagerexample;
    import io.flutter.app.FlutterApplication;
    import io.flutter.plugin.common.PluginRegistry;
    import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
    import io.flutter.plugins.GeneratedPluginRegistrant;

    public class Application extends FlutterApplication implements PluginRegistrantCallback {
        @Override
        public void onCreate() {
            super.onCreate();

            AlarmService.setPluginRegistrant(this);
        }
        @Override
        public void registerWith(PluginRegistry registry) {
            GeneratedPluginRegistrant.registerWith(registry);
        }
    }



///// When I run this code it gives error in console as given below://////

E/flutter ( 6831): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference, null)
E/flutter ( 6831): #0      JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:149:7)
E/flutter ( 6831): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33)
E/flutter ( 6831): <asynchronous suspension>
E/flutter ( 6831): #2      AndroidAlarmManager.initialize (package:android_alarm_manager/android_alarm_manager.dart:76:10)
E/flutter ( 6831): <asynchronous suspension>
E/flutter ( 6831): #3      main (package:alarmdemo/main.dart:12:29)
E/flutter ( 6831): <asynchronous suspension>
E/flutter ( 6831): #4      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
E/flutter ( 6831): #5      _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 6831): #6      _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 6831): #7      _runZoned (dart:async/zone.dart:1516:10)
E/flutter ( 6831): #8      runZoned (dart:async/zone.dart:1500:12)
E/flutter ( 6831): #9      _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
E/flutter ( 6831): #10     _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
E/flutter ( 6831): #11     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
E/flutter ( 6831): 
E/flutter ( 6831): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method AlarmService.initialized on channel plugins.flutter.io/android_alarm_manager_background)
E/flutter ( 6831): #0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:300:7)
E/flutter ( 6831): <asynchronous suspension>
E/flutter ( 6831): #1      _alarmManagerCallbackDispatcher (package:android_alarm_manager/android_alarm_manager.dart:49:12)
E/flutter ( 6831): #2      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
E/flutter ( 6831): #3      _rootRun (dart:async/zone.dart:1124:13)
E/flutter ( 6831): #4      _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter ( 6831): #5      _runZoned (dart:async/zone.dart:1516:10)
E/flutter ( 6831): #6      runZoned (dart:async/zone.dart:1500:12)
E/flutter ( 6831): #7      _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
E/flutter ( 6831): #8      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
E/flutter ( 6831): #9      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
E/flutter ( 6831): 

This is my Updated Code:

/////////////main.dart//////////

    void printHello() {
      final DateTime now = new DateTime.now();
      final int isolateId = Isolate.current.hashCode;
      print("[$now] Hello, world! isolate=${isolateId} 
      function='$printHello'");
    }

    void main() async {
    runApp(MaterialApp(home: Application()));
    }

     class Application extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            child: Center(
              child: RaisedButton(
                child: Text('Hello'),
                onPressed: () {
                  runAlarm();
                },
              ),
            ),
          ),
        );
      }

  void runAlarm() {
    AndroidAlarmManager.oneShot(
      Duration(seconds: 10),
      0,
      printHello,
      wakeup: true,
    ).then((val) => print(val));
  }
  static void alarmTest() {
    print("test");
  }

}

It does not give any Error in console but print two statements as below:

E/AlarmService(11943): Fatal: failed to find callback
I/AlarmService(11943): AlarmService has not yet started.


I also initialize the alarm manager but it gives error in console:


 void runAlarm() {
    AndroidAlarmManager.periodic(
      Duration(seconds: 10),
      0,
      printHello,
      wakeup: true,
    ).then((val) => print(val)).catchError((e) {
      print(e);
    });
  }


Error:

E/flutter ( 6831): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(error, Attempt to invoke interface method 'void io.flutter.plugin.common.PluginRegistry$PluginRegistrantCallback.registerWith(io.flutter.plugin.common.PluginRegistry)' on a null object reference, null)
    E/flutter ( 6831): #0      JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:149:7)
    E/flutter ( 6831): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:302:33)
    E/flutter ( 6831): <asynchronous suspension>
    E/flutter ( 6831): #2      AndroidAlarmManager.initialize (package:android_alarm_manager/android_alarm_manager.dart:76:10)
    E/flutter ( 6831): <asynchronous suspension>
    E/flutter ( 6831): #3      main (package:alarmdemo/main.dart:12:29)
    E/flutter ( 6831): <asynchronous suspension>
    E/flutter ( 6831): #4      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
    E/flutter ( 6831): #5      _rootRun (dart:async/zone.dart:1124:13)
    E/flutter ( 6831): #6      _CustomZone.run (dart:async/zone.dart:1021:19)
    E/flutter ( 6831): #7      _runZoned (dart:async/zone.dart:1516:10)
    E/flutter ( 6831): #8      runZoned (dart:async/zone.dart:1500:12)
    E/flutter ( 6831): #9      _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
    E/flutter ( 6831): #10     _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
    E/flutter ( 6831): #11     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
    E/flutter ( 6831): 
    E/flutter ( 6831): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: MissingPluginException(No implementation found for method AlarmService.initialized on channel plugins.flutter.io/android_alarm_manager_background)
    E/flutter ( 6831): #0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:300:7)
    E/flutter ( 6831): <asynchronous suspension>
    E/flutter ( 6831): #1      _alarmManagerCallbackDispatcher (package:android_alarm_manager/android_alarm_manager.dart:49:12)
    E/flutter ( 6831): #2      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:189:25)
    E/flutter ( 6831): #3      _rootRun (dart:async/zone.dart:1124:13)
    E/flutter ( 6831): #4      _CustomZone.run (dart:async/zone.dart:1021:19)
    E/flutter ( 6831): #5      _runZoned (dart:async/zone.dart:1516:10)
    E/flutter ( 6831): #6      runZoned (dart:async/zone.dart:1500:12)
    E/flutter ( 6831): #7      _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:180:5)
    E/flutter ( 6831): #8      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:300:19)
    E/flutter ( 6831): #9      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
    E/flutter ( 6831): 

enter image description here


Get this bounty!!!