Import variables from another .dart file to .dart file in flutter - flutter

My globals.dart file in same directory:
var apiKey= "AAAAXeuC-XXXXXXXXXXXXXXXXXXXXXXXXXX0rKLb2CWty0MHUzaZ";
var appId= "1:40338f8d8e";
var messagingSenderId= "40338";
var projectId="XXXXXXXXXXXXX";
var databaseURL= "XXXXXXXXXXXX";
I want to import these variables to main.dart file in android studio.
How I did??
import 'globals.dart' as globals;
Imported correctly, no errors
How I used??
apiKey: globals.apiKey
Its inside,
if(Firebase.apps.isNotEmpty){
await Firebase.initializeApp(
name: "HCchatbot",
options: const FirebaseOptions(
apiKey: ,
appId: ,
messagingSenderId:,
projectId: ,
databaseURL:"
),
);
}
The error:
lib/main.dart:12:27: Error: Not a constant expression.
apiKey: globals.apiKey,
^^^^^^
lib/main.dart:11:22: Error: Constant evaluation error:
options: const FirebaseOptions(
^
lib/main.dart:12:27: Context: The invocation of 'apiKey' is not allowed in a constant expression.
apiKey: globals.apiKey,
^
Can somebody help me out?? Thanks in advance

all of your values in globals.dart should be turned to const values =>
const String apiKey= "AAAAXeuC-XXXXXXXXXXXXXXXXXXXXXXXXXX0rKLb2CWty0MHUzaZ";
const String appId= "1:40338f8d8e";
const String messagingSenderId= "40338";
const String projectId="XXXXXXXXXXXXX";
const String databaseURL= "XXXXXXXXXXXX";
try again and it should work.
another solution is removing the const in the FirebaseOptions
options: FirebaseOptions

Related

TypeError: Cannot read properties of undefined (reading 'init') || Flutter web

I have recently upgraded my flutter project from Flutter Beta to Flutter Stable 3.3.8.
after upgrading, I also upgraded all the firebase packages to the latest version.
Due to this upgrade on my config function, there is a new parameter of navigatorKey.
So I included that like this
class NavKey{
static final navKey = GlobalKey<NavigatorState>();
}
static final Config config = Config(
navigatorKey: NavKey.navKey, //new parameter of navigatorKey
tenant: "xx-3066-xx-xx-xx",
clientId: "xx-ad66-xx-a6e6-xx",
scope: "api://xx-xx-422a-a6e6-xx/xx",
redirectUri:
"xx://com.example.xx/xx%xx%3D");
Now If I run my project and enter my email id and hit enter it shows this error
TypeError: Cannot read properties of undefined (reading 'init')
on my void main() I have included all my Firebase initialize like this
Future<void> main() async {
// await dotenv.load();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "xxx-xx",
authDomain: "xx-xxx.firebaseapp.com",
databaseURL: "https://xxx-xx-default-xxx.xx.com",
projectId: "xxx-xxx",
storageBucket: "xxx-xx.appspot.com",
messagingSenderId: "xxx",
appId: "1:xx:web:xxx3d75b63xxxxe9",
measurementId: "G-xxxx")
);
runApp(const MyApp()
/* MaterialApp(//
home: MyApp())*/
);
}
on my index.html I have also included this script as I am running my project on flutter web
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-functions.js"></script>
These are my all errors
Well, I am not able to find the solution for the latest package.
That's why I rolled back my aad_oauth from ^0.4.0 to ^0.3.0 where it doesn't asked for navigatorKey
Config(
navigatorKey: NavKey.navKey,)

Firebase RTDB Flutter app: Multiple Databases

So, I am using the Blaze plan in Firebase and I have multiple realtime databases. I was wondering how I can connect to a specific one through my Flutter app.
FirebaseDatabase.instance.reference(); connects me to the default database, but how can I connect to another one?
Using FirebaseDatabase.instance is just a shorthand notation to getting the default FirebaseApp instance, which is typically auto-initialized from the values in your google-services.json/google-services.info.plist
You can explicitly initialize a FirebaseApp with configuration data in your code. A snippet of the relevant code from an app I happen to be working on:
final FirebaseApp app = await FirebaseApp.configure(
name: "defaultAppName",
options: Platform.isIOS
? const FirebaseOptions(
googleAppID: '....',
gcmSenderID: '...',
databaseURL: '...',
)
: const FirebaseOptions(
googleAppID: '...',
apiKey: '...',
databaseURL: '...',
),
);*/
FirebaseDatabase(app: app).setPersistenceEnabled(true);
FirebaseDatabase(app: app).reference().child("/rounds/r1").orderByValue().onChildAdded.forEach((event) => {
print(event.snapshot.value)
});

The named parameter 'options' isn't defined

I am creating an app to send data to database where I am using this piece of code and "The named parameter 'options' isn't defined" this problem is appearing.
final FirebaseApp app = FirebaseApp(
options: FirebaseOptions(
googleAppID: '',
apiKey: '',
databaseURL: '',
)
);
Use the documentation: https://pub.dev/documentation/firebase_core/latest/firebase_core/FirebaseApp-class.html
FireBaseApp has a static method named .configure that accepts a String name and FireBaseOptions options that returns an existing unmodified Future<FireBaseApp> or a new configured Future<FireBaseApp> asynchronously.

Where can i find google app id, api key, project id and gcm sender id in cloud firestore

I had this sample code, but I am not sure where can I find all the fields in my Firebase console.
final FirebaseApp app = await FirebaseApp.configure(
name: 'test',
options: const FirebaseOptions(
googleAppID: '1:1234567:ios:987654',
gcmSenderID: '987654321',
apiKey: 'ABC123456789DEF',
projectID: 'projectId',
),
);
You can find it in GoogleServicesInfo.plist file.
You should be able to see like:
<key>GOOGLE_APP_ID</key>
<string>1:111111:ios:222222</string>
<key>GCM_SENDER_ID</key>
<string>1234567890</string>
<key>API_KEY</key>
<string>ThisIsMyApiKey111</string>
<key>PROJECT_ID</key>
<string>yourId</string>

Write test axios-mock-adapter with axios.create()

I want to test my http service but get error.
So, my test file
api.js
import axios from 'axios';
export const api = axios.create();
fetchUsers.js
import api from './api';
export const fetchUsers = (params) api.get('/api/users', { params })
.then(({data}) => data)
fetchUsers.spec.js
import MockAdapter from 'axios-mock-adapter'
import api from './api';
const mock = new MockAdapter(api);
describe('fetchUsers', () => {
it('should send request', (done) => {
const data = { data: ['user'] };
mock.onGet('/api/users').reply(200, data);
fetchUsers().then((response) => {
expect(response).toEqual(data.data);
done();
});
});
});
But I get error here
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1158:14)
If I replace in api.js axios.create() with axios its' working. But how to test with created axios instance? I'll need to ass there parameters when create it.
Anyone can help with that?
Hi I had the same issue and had to answer myself here https://stackoverflow.com/a/51414152/73323
Here is the gist:
First off, you don't need the axios-mock-adapter library.
Create a mock for axios in src/__mocks__:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
Then in your test file, the gist would look like:
import mockAxios from 'axios'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
// for some reason i need this to fix reducer keys undefined errors..
jest.mock('../../store/rootStore.ts')
// you need the 'async'!
test('Retrieve transaction data based on a date range', async () => {
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore()
const mockData = {
'data': 123
}
/**
* SETUP
* This is where you override the 'post' method of your mocked axios and return
* mocked data in an appropriate data structure-- {data: YOUR_DATA} -- which
* mirrors the actual API call, in this case, the 'reportGet'
*/
mockAxios.post.mockImplementationOnce(() =>
Promise.resolve({ data: mockData }),
)
const expectedActions = [
{ type: REQUEST_TRANSACTION_DATA },
{ type: RECEIVE_TRANSACTION_DATA, data: mockData },
]
// work
await store.dispatch(reportGet())
// assertions / expects
expect(store.getActions()).toEqual(expectedActions)
expect(mockAxios.post).toHaveBeenCalledTimes(1)
})